Vue中动态Class实战

效果展示

Vue中动态Class实战

需求

想实现一个假如有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>


原文始发于微信公众号(醉鱼Java):Vue中动态Class实战

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/231464.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!