Vue中動態(tài)Class實戰(zhàn)示例
更新時間:2023年11月21日 09:22:43 作者:醉魚
這篇文章主要為大家介紹了Vue中動態(tài)Class的實戰(zhàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
需求
想實現(xiàn)一個假如有5個div塊,默認都是灰色,鼠標懸浮到哪個div上,那個div就顯示為黑色。
具體的實現(xiàn)業(yè)務邏輯可根據(jù)這個進行演變
設計
通過動態(tài) class 類名來實現(xiàn),實現(xiàn)鼠標懸浮到div時動態(tài)綁定class
版本
- Vue 3.3.4
- Node 20.9.0
代碼
<template>
<div class="container">
<div v-for="(box, index) in boxes" :key="index" :class="'box'+ index"
:style="{ color: box.color, backgroundColor: box.backgroundColor }">
{{ box.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
boxes: [
{ content: 'Box 1', color: 'white', backgroundColor: 'grey' },
{ content: 'Box 2', color: 'white', backgroundColor: 'grey' },
{ content: 'Box 3', color: 'white', backgroundColor: 'grey' },
{ content: 'Box 4', color: 'white', backgroundColor: 'grey' },
{ content: 'Box 5', color: 'white', backgroundColor: 'grey' }
]
};
},
methods: {
handleMouseOver(index) {
console.log('鼠標移入:',index)
this.boxes[index].backgroundColor = 'black';
this.boxes[index].color = 'white';
},
handleMouseOut(index) {
console.log('鼠標移出:',index)
this.boxes[index].backgroundColor = 'grey';
this.boxes[index].color = 'white';
}
},
mounted() {
this.boxes.forEach((box, index) => {
console.log("頁面初始化:",box,index)
this.$el.querySelector('.box'+index).addEventListener('mouseover', () => this.handleMouseOver(index));
this.$el.querySelector('.box'+index).addEventListener('mouseout', () => this.handleMouseOut(index));
});
}
};
</script>以上就是Vue中動態(tài)Class實戰(zhàn)示例的詳細內(nèi)容,更多關(guān)于Vue動態(tài)Class的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue實現(xiàn)動態(tài)給data函數(shù)中的屬性賦值
這篇文章主要介紹了vue實現(xiàn)動態(tài)給data函數(shù)中的屬性賦值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

