Vue中動態(tài)Class實戰(zhàn)

效果展示

動態(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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容