1.内联语法
<div id="app1" class="static" v-bind:class="{active:isActive,'text-danger':hasError}"></div>
var app1 = new Vue({
el: "#app1",
data: {
isActive: true,
hasError: false
}
})
<div id="app4" :style="{color:activeColor,fontSize:fontSize+'px'}"></div>
var app4 = new Vue({
el: "#app4",
data: {
activeColor: 'red',
fontSize: 30
}
})
2.对象语法
<div v-bind:class="classObject">传对象</div>
var app1 = new Vue({
el: "#app1",
data: {
classObject: {
active: true,
'text-danger': true
}
}
})
<div id="app5" :style="styleObject">#样式对象</div>
var app5 = new Vue({
el: "#app5",
data: {
styleObject: {
color: '#4848',
fontSize: '13px'
}
}
})
3.数组语法
<div id="app3" v-bind:class="[activeClass,errorClass]">数组</div>
var app3 = new Vue({
el: "#app3",
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
})
例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<h3>class</h3>
<h4>#对象语法</h4>
<div id="app1" class="static" v-bind:class="{active:isActive,'text-danger':hasError}">
<div v-bind:class="classObject">传对象</div>
</div>
<div id="app2" v-bind:class="classObject1">计算属性</div>
</div>
<h4>#数组语法</h4>
<div id="app3" v-bind:class="[activeClass,errorClass]">数组</div>
<a href="https://cn.vuejs.org/v2/guide/class-and-style.html#用在组件上">用在组件上</a>
<h3>style</h3>
<div id="app4" :style="{color:activeColor,fontSize:fontSize+'px'}">
#对象语法
</div>
<div id="app5" :style="styleObject">#样式对象</div>
</body>
</html>
<script>
var app1 = new Vue({
el: "#app1",
data: {
isActive: true,
hasError: false,
classObject: {
active: true,
'text-danger': true
}
}
})
var app2 = new Vue({
el: "#app2",
data: {
isActive: true,
error: null
},
computed: {
classObject1: function() {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
})
var app3 = new Vue({
el: "#app3",
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
})
var app4 = new Vue({
el: "#app4",
data: {
activeColor: 'red',
fontSize: 30
}
})
var app5 = new Vue({
el: "#app5",
data: {
styleObject: {
color: '#4848',
fontSize: '13px'
}
}
})
</script>