操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
1.理解 在应用界面中, 某个(些)元素的样式是变化的 class/style绑定就是专门用来实现动态样式效果的技术
2.class绑定:
语法 v-bind:class=‘xxx’
xxx是字符串
xxx是对象
xxx是数组
3.style绑定 :style="{color:activeColor,fontSize:fontSize+‘px’}" 其中activeColor/fontSize是data属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
.aClass{
color:red;
}
.bClass{
color: #0000FF;
}
.cClass{
font-size: 20px;
}
</style>
</head>
<body>
<div id="demo">
<h2>1.class的绑定</h2>
<p class="cClass" :class="a">xxx是字符串</p>
<p :class="{aClass: isA, bClass: isB}">xxx是对象</p>
<p :class="['aClass', 'bClass']">xxx是对象</p>
<h2>2.style绑定</h2>
<p :style="{color:activeColor,fontSize:fontSize+'px'}">我在做style绑定</p>
<button type="button" @click="update">更新</button>
</div>
<script type="text/javascript">
new Vue({
el: '#demo',
data:{
a: 'aClass',
isA: true,
isB: false,
activeColor: 'red',
fontSize: 20
},
methods:{
update(){
this.a = 'bClass';
this.isA = false;
this.isB = true;
this.activeColor = 'green';
this.fontSize = '40'
}
}
})
</script>
</body>
</html>
其他:
1 自动添加前缀
当 v-bind:style 使用需要添加浏览器引擎前缀的 CSS 属性时,如 transform,Vue.js 会自动侦测并添加相应的前缀。
2数组语法
v-bind:style 的数组语法可以将多个样式对象应用到同一个元素上: