操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="app">
<h1>动态CSS Class</h1>
<h2>示例1</h2>
<div v-on:click="changeColor = !changeColor" v-bind:class="{changeColor:changeColor}">
<span>Herry</span>
</div>
<button v-on:click="changeColor= !changeColor">change Color</button>
<button v-on:click="changeLength = !changeLength">changeLength</button>
<h2>示例2</h2>
<div v-bind:class="compClass">
<span>Herry</span>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
new Vue({
el: '#app',
data: {
changeColor: false,
changeLength: false
},
methods: {
},
computed: {
compClass: function() {
return {
changeColor: this.changeColor,
changeLength: this.changeLength
}
}
}
});
style.css
span {
background: red;
display: inline-block;
padding: 10px;
color: #fff;
margin: 10px 0;
}
.changeColor span {
background-color: green;
}
.changeLength span:after {
content: "length";
margin-left: 10px;
}