效果展示
需求
想实现一个假如有5个div块,默认都是灰色,鼠标悬浮到哪个div上,那个div就显示为黑色。
具体的实现业务逻辑可根据这个进行演变
设计
通过动态 class 类名来实现,实现鼠标悬浮到div时动态绑定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>