Class与Style绑定
操作元素的class列表和内联样式是数据绑定的一个常见需求,因为他们都是属性,所以我们可以用v-bind处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将v-bind用于class和style时,Vue.js做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或者数组。
绑定HTML
对象语法
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="vue.js"></script>
</head>
<body>
<div id='app'>
<div v-bind:class="{active:isActive}"
style="width:200px;height:200px;text-align:center;line-height:200px;">
<!-- 是否绑定active属性取决于isActive的值 -->
hi vue!
</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el:'#app',
data: {
isActive:true,//将active属性绑定到div上
},
})
</script>
<style>
.active {
background: red;
}
</style>
</body>
</html>
不可以在对象中传入多个属性来动态切换多个class,此外v-bind:class指令也可以和普通的class属性共存。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="vue.js"></script>
</head>
<body>
<div id='app'>
<div class="test" v-bind:class="{active:isActive, green:isGreen}"
style="width:200px;height:200px;text-align:center;line-height:200px;">
<!-- 其可与静态的class属性并存 -->
hi vue!
</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el:'#app',
data: {
isActive:true,//将active属性绑定到div上
isGreen:true,
},
})
</script>
<style>
.test {
font-size: 40px;
}
.green{
color:green;
}
.active {
background: red;
}
</style>
</body>
</html>
其同时支持数组形式(静态),通过如下命令添加active和green样式:
v-bind:class="['active', 'green']"
可用三元运算符的形式动态赋值:
v-bind:class="[isActive ? 'active' : '', isGreen ? 'green' : '']"
绑定内联样式
#对象语法
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="vue.js"></script>
</head>
<body>
<div id='app'>
<div v-bind:style="{color:color, fontSize:size, background: isRed ? 'red' : ''}">
hi vue!
</div>
<!-- style对象的属性值使用驼峰式命名法则 -->
</div>
<script type="text/javascript">
var vm = new Vue({
el:'#app',
data: {
color: "green",
size: "300px",
isRed: true,
},
})
</script>
</body>
</html>
内联style属性则不需要在用