數據綁定的一個常見需求場景是操縱元素的 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>
更多: