Vue中動(dòng)態(tài)Class實(shí)戰(zhàn)示例
需求
想實(shí)現(xiàn)一個(gè)假如有5個(gè)div塊,默認(rèn)都是灰色,鼠標(biāo)懸浮到哪個(gè)div上,那個(gè)div就顯示為黑色。
具體的實(shí)現(xiàn)業(yè)務(wù)邏輯可根據(jù)這個(gè)進(jìn)行演變
設(shè)計(jì)
通過(guò)動(dòng)態(tài) class 類名來(lái)實(shí)現(xiàn),實(shí)現(xiàn)鼠標(biāo)懸浮到div時(shí)動(dòng)態(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("頁(yè)面初始化:",box,index)
this.$el.querySelector('.box'+index).addEventListener('mouseover', () => this.handleMouseOver(index));
this.$el.querySelector('.box'+index).addEventListener('mouseout', () => this.handleMouseOut(index));
});
}
};
</script>以上就是Vue中動(dòng)態(tài)Class實(shí)戰(zhàn)示例的詳細(xì)內(nèi)容,更多關(guān)于Vue動(dòng)態(tài)Class的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
實(shí)時(shí)通信Socket?io的使用示例詳解
這篇文章主要為大家介紹了實(shí)時(shí)通信Socket?io的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
vue實(shí)現(xiàn)動(dòng)態(tài)給data函數(shù)中的屬性賦值
這篇文章主要介紹了vue實(shí)現(xiàn)動(dòng)態(tài)給data函數(shù)中的屬性賦值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
vue父子組件動(dòng)態(tài)傳值的幾種方式及注意問(wèn)題詳解
這篇文章主要介紹了vue父子組件動(dòng)態(tài)傳值的幾種方式及注意問(wèn)題詳解,需要的朋友可以參考下2022-12-12
Vue.js動(dòng)態(tài)添加、刪除選題的實(shí)例代碼
這篇文章主要介紹了Vue.js動(dòng)態(tài)添加、刪除選題的實(shí)例代碼,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09
vue項(xiàng)目netWork地址無(wú)法訪問(wèn)的問(wèn)題及解決
這篇文章主要介紹了vue項(xiàng)目netWork地址無(wú)法訪問(wèn)的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09

