数据绑定的一个常见需求场景是操纵元素的 CSS class 列表和内联样式。因为 class
和 style
都是 attribute,我们可以和其他 attribute 一样使用 v-bind
将它们和动态的字符串绑定。但是,在处理比较复杂的绑定时,通过拼接生成字符串是麻烦且易出错的。因此,Vue 专门为 class
和 style
的 v-bind
用法提供了特殊的功能增强。除了字符串外,表达式的值也可以是对象或数组。
一、绑定Class
<div class="item" :class="{ active: activeIndex == index }" v-for="(item, index) in students" @click="itemClick(index)">学生编号:{{ item.id }}学生姓名:{{ item.name }}</div>
css
<style>
.item {background-color: rgb(180, 180, 180);padding: 20px;border-bottom: 1px solid red;transition: all ease 1s;
}.item.active {background-color: red;color: white;font-size: 20px;
}
</style>
js
<script>
export default {data() {return {students: [{ id: 1, name: '张三' },{ id: 2, name: '李四' },{ id: 3, name: '王五' },{ id: 4, name: '赵六' },],activeIndex: -1}},methods: {itemClick(e) {console.info(e);this.activeIndex = e;}}
}
</script>
二、绑定内联样式,绑定style
<div class="item" :style="{ color: activeIndex == index?'red':'blue' }" v-for="(item, index) in students" @click="itemClick(index)">学生编号:{{ item.id }}学生姓名:{{ item.name }}</div>
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
更多: