Vue中动态Class实战

效果展示

动态class.gif

需求

想实现一个假如有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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容