绑定方式:数组语法
用法一:直接通过[]绑定一个类
<h2 :class="['active']">{{message}}</h2>
用法二:也可以传入多个值
<h2 :class=“[‘active’, 'line']">{{message}}</h2>
用法三:和普通的类同时存在,并不冲突
注:会有title/active/line三个类
<h2 class="title" :class=“[‘active’, 'line']">{{message}}</h2>
用法四:如果过于复杂,可以放在一个methods或者computed中
注:classes是一个计算属性
<h2 class="title" :class="classes">{{message}}</h2>
注:getClasses()是一个方法
<h2 :class="getClasses()">{{message}}</h2>
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.active{
color: red;
}
</style>
</head>
<body>
<div id="app">
<h2 :class="['active','line']">用法一:{{message}}</h2>
<h2 :class="[active,line]">用法二:{{message}}</h2>
<h2 :class="[active,line]" class="title">用法三:{{message}}</h2>
<h2 :class="getClasses()">用法四(方法methods):{{message}}</h2>
<h2 :class="classes">用法四(计算属性computed){{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: '你好啊',
active:'active',
line:'bbbbbbbbbb'
},
methods:{
getClasses: function () {
return [this.active,this.line]
}
},
computed: {
classes: function () {
return [this.active,this.line]
}
}
})
</script>
</body>
</html>
效果
绑定方式:对象语法
用法一:直接通过{}绑定一个类
<h2 :class="{'active': isActive}">{{message}}</h2>
用法二:也可以通过判断,传入多个值
<h2 :class="{'active': isActive, 'line': isLine}">{{message}}</h2>
用法三:和普通的类同时存在,并不冲突
注:如果isActive和isLine都为true,那么会有title/active/line三个类
<h2 class="title" :class="{'active': isActive, 'line': isLine}">{{message}}</h2>
用法四:如果过于复杂,可以放在一个methods或者computed中
注:classes是一个计算属性
<h2 class="title" :class="classes">Hello World</h2>
注:getClasses()是一个方法
<h2 class="title" :class="getClasses()">Hello World</h2>
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.active{
color: red;
}
</style>
</head>
<body>
<div id="app">
<h2 :class="{active: isAcitve}">用法一:{{message}}</h2>
<h2 :class="{active:isAcitve,line:isLine}">用法二:{{message}}</h2>
<h2 class="title" :class="{active:isAcitve,line:isLine}">用法三:{{message}}</h2>
<h2 :class="getClasses()">用法四(方法methods):{{message}}</h2>
<h2 :class="classes">用法四(计算属性computed):{{message}}</h2>
<button v-on:click="btnClick">按钮</button>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: '你好啊',
active:'active',
isAcitve:true,
isLine:true
},
methods:{
btnClick: function () {
this.isAcitve = !this.isAcitve
},getClasses:function () {
return {active:this.isAcitve,line:this.isLine}
}
},
computed: {
classes: function () {
return {active:this.isAcitve,line:this.isLine}
}
}
})
</script>
</body>
</html>
效果