一.动态绑定class
1.对象语法
可以绑定到一个对象,方法或者计算属性中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<!--<h2 :class="{类名1: true, 类名2: boolean}">{{message}}</h2>-->
// 普通绑定的title和动态绑定的类在vue内容会统一整合
<h2 class="title" :class="{active: isActive, line: isLine}">{{message}}</h>
<h2 class="title" :class="getClasses()">{{message}}</h2>
<h2 class="title" :class="{active: classData}">{{message}}</h2>
<button @click="btnClick">按钮</button>
<script>
const app = new Vue({
el: '#app',
data: {
message: '你好啊',
isActive: true,
isLine: true
},
methods: {
btnClick: function () {
this.isActive = !this.isActive
},
getClasses: function () {
return {active: this.isActive, line: this.isLine}
}
},
computed:{
classData(){
return this.isActive
}
}
})
</script>
</body>
</html>
2.数组语法
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.active {
color: red;
}
.line {
color:blue
}
</style>
</head>
<body>
// 普通绑定的title和动态绑定的类在vue内容会统一整合
// 具有 title isActive isLine 三种类
<h2 class="title" :class="[isActive,isLine]">{{message}}</h>
// 具有 title isActive isLine 三种类
<h2 class="title" :class="['aisActive','line']">{{message}}</h>
<h2 class="title" :class="getClasses()">{{message}}</h2>
<button @click="btnClick">按钮</button>
<script>
const app = new Vue({
el: '#app',
data: {
message: '你好啊',
isActive: 'active',
isLine: 'line'
},
methods: {
btnClick: function () {
this.isActive = !this.isActive
},
getClasses: function () {
return [this.isActive, this.isLine]
}
}
})
</script>
</body>
</html>
二.动态绑定style
1.对象绑定
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--<h2 :style="{key(属性名): value(属性值)}">{{message}}</h2>-->
<!--'50px'必须加上单引号, 否则是当做一个变量去解析-->
<!--<h2 :style="{fontSize: '50px'}">{{message}}</h2>-->
<!--finalSize当成一个变量使用-->
<h2 :style="{fontSize: finalSize}">{{message}}</h2>
<h2 :style="{fontSize: finalSize1 + 'px', backgroundColor: finalColor}">{{message}}</h2>
<h2 :style="getStyles()">{{message}}</h2>
<script>
const app = new Vue({
el: '#app',
data: {
message: '你好啊',
finalSize: '100px',
finalSize1: 100,
finalColor: 'red'
}
methods: {
getStyles: function () {
return {fontSize: this.finalSize + 'px', backgroundColor: this.finalColor}
}
}
})
</script>
</body>
</html>
2.数组绑定
<div id="app">
<h2 :style="[baseStyle, baseStyle1]">{{message}}</h2>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: '你好啊',
baseStyle: {backgroundColor: 'red'},
baseStyle1: {fontSize: '100px'},
}
})
</script>