简介
v-bind提供属性绑定,即M层数据–>V层。
<body>
<div id="content">
<input type="text" value="" />
</div>
</body>
<script>
var vm = new Vue({
el:"#content",
data:{
msg:"默认值"
}
});
</script>
此时如果想往input中插入自定义数据msg,必须用v-bind:value=“msg”,而不能直接value=“msg” :
<input type="text" value="msg" /> //显示“msg”
<input type="text" v-bind:value="msg" /> //显示“默认值”
<input type="text" :value="msg" /> //v-bind:value的简写,显示“默认值”
同时v-bind也支持js表达式:
<input type="text" :value="msg + '123'" /> //显示“默认值123”
class与style绑定
class与style绑定可通过v-bind实现,各有三种语法:
- 内联语法
- 对象语法
- 数组语法
v-bind:class 指令:
必须使用bool方式,可以与普通的 class 属性共存。可以在对象中传入计算属性来动态切换多个 class。
v:bind:style 指令:
对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象。CSS 属性名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名。
使用需要添加浏览器引擎前缀的 CSS 属性时,如 transform,Vue.js 会自动侦测并添加相应的前缀。
class绑定
内联语法
//常规写法
<button class="btn btn-primary">按钮</button>
//内联语法bind
<button class="btn" v-bind:class="{ 'btn-primary':true }">按钮</button>
对象语法
//常规写法
<button class="btn btn-primary">按钮</button>
//对象语法bind
<button class="btn" v-bind:class="myClass">按钮</button>
var vmContent = new Vue({
el: "#classContent",
data: {
myClass:{'btn-primary':true}
}
});
数组语法
//常规写法
<button class="btn btn-primary disabled">按钮</button>
//数组语法bind
<button class="btn" v-bind:class="[myClass,myClass2]">按钮</button>
var vmContent = new Vue({
el: "#classContent",
data: {
myClass:{'btn-primary':true},
myClass2:{'disabled':true}
}
});
style绑定
内联语法
//常规写法
<p style="color: red;">样式1</p>
//内联语法bind
<p v-bind:style="{color:'red'}">样式1</p>
对象语法
//常规写法
<p style="color: green; font-size: 20px;">样式2</p>
//对象语法bind
<p v-bind:style="myStyle">样式2</p>
var vmStyle = new Vue({
el:"#styleContent",
data:{
myStyle:{color: 'green',fontSize:'20px'},
}
});
数组语法
//常规写法
<p style="color: green; font-size: 20px; font-weight: bold;">样式2</p>
//数组语法bind
<p v-bind:style="[myStyle,myStyle2]">样式3</p>
var vmStyle = new Vue({
el:"#styleContent",
data:{
myStyle:{color: 'green',fontSize:'20px'},
myStyle2:{'font-weight':'bold'}
}
});