效果展示

動態(tài)class.gif
需求
想實現(xiàn)一個假如有5個div塊,默認(rèn)都是灰色,鼠標(biāo)懸浮到哪個div上,那個div就顯示為黑色。
具體的實現(xiàn)業(yè)務(wù)邏輯可根據(jù)這個進(jìn)行演變
設(shè)計
通過動態(tài) class 類名來實現(xiàn),實現(xiàn)鼠標(biāo)懸浮到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('鼠標(biāo)移入:',index)
this.boxes[index].backgroundColor = 'black';
this.boxes[index].color = 'white';
},
handleMouseOut(index) {
console.log('鼠標(biāo)移出:',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>