完整源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!--class字符串写法-->
<div class="basic" :class="str">你好</div><br><br>
<!--class数组写法-->
<div class="basic" :class="classArr">你好</div><br><br>
<input type="button" @click="bigFont" value='字体变大'></button><br><br>
<!--class对象写法-->
<div class="basic" :class="classObj">你好</div><br><br>
<input type="button" @click="backgroundColor" value='背景变色'></button><br><br>
<!--style对象写法,数组写法比较少这里不介绍-->
<div class="basic" :style="styleObj">你好</div><br><br>
<input type="button" @click="changeFontSize" :value='isSmall?"字体变大":"字体变小"' />
</div>
</body>
<script>
const vm = new Vue({
el:'#root',
data() {
return {
str:'smallFont',
classArr:[],
classObj:{
backgroundColor:false //false表示不使用该class
},
styleObj:{
fontSize : ''
},
isSmall:false
}
},
methods: {
bigFont(){
this.classArr.push('bigFont')
},
backgroundColor(e){
this.classObj.backgroundColor = !this.classObj.backgroundColor
this.classObj.backgroundColor?e.target.value = '恢复原色':e.target.value = '背景变色'
},
changeFontSize(){
this.isSmall = !this.isSmall
if(this.isSmall) this.styleObj.fontSize = '15px'
else this.styleObj.fontSize = '30px'
}
}
})
</script>
<style>
.basic{
font-size: 30px;
color: red;
}
.smallFont{
font-size: 15px;
}
.bigFont{
font-size: 50px;
}
.backgroundColor{
background-color: aqua;
}
</style>
</html>
代码解析
1. 动态绑定 class 的三种方式
(1)字符串写法
<div class="basic" :class="str">你好</div>
- 特点:通过字符串指定类名,适用于类名不确定的场景
- 原理:
str
的值为smallFont
,初始时会在basic
类基础上添加smallFont
类
(2)数组写法
<div class="basic" :class="classArr">你好</div>
<input type="button" @click="bigFont" value='字体变大'>
- 特点:通过数组存储多个类名,适用于需要动态添加类名的场景
- 原理:点击按钮时,调用
bigFont
方法向classArr
数组中添加bigFont
类
(3)对象写法
<div class="basic" :class="classObj">你好</div>
<input type="button" @click="backgroundColor" value='背景变色'>
- 特点:通过对象的键值对(键为类名,值为布尔值)控制类是否生效,适用于样式切换场景
- 原理:点击按钮时切换
classObj.backgroundColor
的值(true/false),控制backgroundColor
类是否生效
2. 动态绑定 style 的方式
<div class="basic" :style="styleObj">你好</div>
<input type="button" @click="changeFontSize" :value='isSmall?"字体变大":"字体变小"' />
- 特点:通过对象直接绑定行内样式,适用于需要动态设置具体样式值的场景
- 原理:点击按钮时切换
isSmall
的值,根据其值设置styleObj.fontSize
的具体大小
3. 小结
:class
和:style
是 Vue 的指令,用于动态绑定样式
- 静态类(如
basic
)和动态类可以同时存在
- 样式切换的核心是通过修改数据(data 中的属性)来驱动视图变化
- class 绑定适用于预定义的 CSS 类,style 绑定适用于需要动态计算的样式值