数据绑定的一个常见需求场景是操纵元素的 CSS class 列表和内联样式。因为 class
和 style
都是 attribute,我们可以和其他 attribute 一样使用 v-bind
将它们和动态的字符串绑定。但是,在处理比较复杂的绑定时,通过拼接生成字符串是麻烦且易出错的。因此,Vue 专门为 class
和 style
的 v-bind
用法提供了特殊的功能增强。除了字符串外,表达式的值也可以是对象或数组。
不管是类class还是样式style,都有对象和数组的写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>15_类与样式绑定</title>
<style>
.a {
font-size: 30px;
}
.b {
color: #f66;
}
</style>
</head>
<body>
<div id="app">
<input type="checkbox" v-model="flag" />
<div class="a b">群组选择器</div>
<!-- 在flag字段为真时,才显示红色的30px的字体 -->
<!-- class对象写法,key为定义的样式,value为条件 -->
<div :class="{ a: flag, b: flag }">class的对象写法</div>
<!-- class数组写法 -->
<div :class="[{a: flag}, {b: flag}]">class数组写法</div>
<!-- 三元运算符 -->
<div :class="flag ? 'a b' : ''">三元运算符 class写法</div>
<!-- style对象写法,小驼峰式以及短横线连接方式 -->
<div :style="{ color: color, fontSize: fontSize }">style对象写法</div>
<!-- style数组写法 -->
<div :style="[{color: color}, {fontSize: fontSize}]">style数组写法</div>
</div>
</body>
<script src="lib/vue.global.js"></script>
<script>
Vue.createApp({
data () {
return {
flag: false,
color: '#00f',
fontSize: '50px'
}
}
}).mount('#app')
</script>
</html>