Vue中动态Class实战

本文介绍了如何使用Vue3.3.4和Node20.9.0环境,通过动态class实现当鼠标悬浮在Vue组件中的div块上时,该div颜色改变。展示了HTML模板、JavaScript逻辑和事件处理方法。
摘要由CSDN通过智能技术生成

效果展示

需求

想实现一个假如有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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值