标签绑定class属性:v-bind:class="{changeColor: true}"
注意里面的写法是对象的形式
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Vue.js</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<!-- vue-app是根容器 -->
<div id="vue-app">
<h1> 动态 CSS Class</h1>
<h2>实例 1</h2>
<div v-on:click="changeColor=!changeColor" v-bind:class="{changeColor: changeColor}">
<span> changeColor </span>
</div>
<h2>实例 2</h2>
<button v-on:click="changeColor=!changeColor"> change color </button>
<button v-on:click="changeLength=!changeLength"> change length </button>
<div v-bind:class="compClasses">
<span>Henry</span>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
css
span {
background: red;
display: inline-block;
padding: 10px;
color: #fff;
margin: 10px 0;
}
.changeColor span {
background : blue;
}
.changeLength span:after {
content: "length";
margin-left: 20px;
}
app.js
'use strict';
// 实例化vue对象
new Vue({
el: "#vue-app",
data: {
changeColor: false,
changeLength: false
},
methods: {
},
computed: {
compClasses: function(){
// 返回的是一个对象
return {
changeColor: this.changeColor,
changeLength: this.changeLength
}
}
}
});