今天我们一起来学一学 VUE的绑定。
一、数据绑定
首先可以先把数据定义在Vue页面中的<script>标签内,然后在<template>标签中通过{{变量名去取}}。
另一种方法:<div v-text="变量名"></div>
如果变量是对象,可以{{对象.属性}}去取。
如果变量是集合,可以通过 v-for 遍历去取。
请看下面实例(我们在新建项目中的App.vue):
<template>
<div id="app">
<h2>hello vue 绑定数据: {{msg}}</h2>
<br>
绑定数据的另一种方法:
<div v-text="msg"></div>
<br>
<h3>{{obj.name}}</h3>
<br>
<hr>
<ul><li v-for ="item in list" >
{{item}}
</li></ul>
<br>
<ul><li v-for ="item in list1" >
{{item.title}}
</li></ul>
<ul><li v-for ="item in list2" >
{{item.cate}}
<ol>
<li v-for ="news in item.list" >
{{news.title}}
</li>
</ol>
</li></ul>
<br>
</div>
</template>
<script>
export default {
name: 'App',
data () { /*业务逻辑里面定义的数据*/
return {
msg: 'Welcome to Your Vue.js App',
obj:{name:"张三"},
flag:false,
list:['111','222','333'],
list1:[
{'title':'1111'},{'title':'2222'},{'title':'2222'}
],
list2:[
{
"cate":"国内新闻",
"list":[
{'title':'国内新闻1111'},
{'title':'国内新闻2222'}
]
},
{
"cate":"国际新闻",
"list":[
{'title':'国际新闻1111'},
{'title':'国际新闻2222'}
]
}
]
}
}
}
</script>
<style>
</style>
二、属性绑定
绑定属性主要使用 v-bind命令。 如:<img v-bind:src="url">
也可以使用省略写法 : 如: <img :src="url">
具体示例代码如下:
<template>
<div id="app">
<h1>绑定属性</h1>
<div v-bind:title="title">aaaa</div>
<img v-bind:src="url">
<br>
另一种写法
<img :src="url">
<br>
绑定html
<div v-html="h"></div>
</div>
</template>
<script>
export default {
name: 'App',
data () { /*业务逻辑里面定义的数据*/
return {
url:"https://cn.vuejs.org/images/vuemastery.png?_sw-precache=6f09ce143467fba22039bde3f2070c19" ,
title:"我是一个标题",
h:'<h2>我是h2</h2>'
}
}
}
</script>
<style>
</style>
样式绑定:
class 与 style 是 HTML 元素的属性,用于设置元素的样式,我们可以用 v-bind 来设置样式属性。
Vue.js v-bind 在处理 class 和 style 时, 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。
内联CSS也可称为行内CSS或者行级CSS,它直接在标签内部引入,显著的优点是十分的便捷、高效;但是同时也造成了不能够重用样式的缺点,如果代码行数到达一定长度不建议采用。通常内联CSS作为测试使用,可以查找代码中bug。内联样式的优先级比选择器优先级要高,且不能重用,请谨慎使用~
<template>
<div id="app">
<!--类选择器样式绑定-->
<div v-bind:class="{active:isActive}"></div>
<br>
<!--内联样式绑定-->
<div v-bind:style="{ width : wid +'px' , height : hei + 'px', background : color }"></div>
</div>
</template>
<script>
export default {
data(){
return {
isActive: true,
wid:100,
hei:100,
color:"red",
actactiveColor:'red',
fontSize:100
}
}
}
</script>
<style lang="scss">
.active {
width: 100px;
height: 100px;
background: green;
}
</style>
四、双向数据绑定
v-model 指令用来在 input、select、textarea、checkbox、radio 等表单控件元素上创建双向数据绑定,根据表单上的值,自动更新绑定的元素的值。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。
下面是一个简单的示例,大家可以尝试一下,就会明白其中含义。
<template>
<div id="app">
<input v-model="message">
<br>
<br>
下面是复读机,通过input框的输入影响了message的值,message的值改变又显示在下方,这就是双向绑定
<div v-bind:class="{active:flag}">{{message}}</div>
</div>
</template>
<script>
export default {
data(){
return {
message:"",
flag:true
}
}
}
</script>
<style lang="scss">
.active {
width: 145px;
height: 20px;
background: grey;
}
</style>