樣圖:
思路:
動態綁定class,用@mouseenter()綁定一個事件,並將列的索引index傳入,然后在data里建一個變量來保存,默認-1 0的話頁面刷新后第一個背景色就已經顯示了
html
<div class="item" v-for="(one, index) in categoryList" :key="one.categoryId" :class="{ cur: bgcolor === index }" > <h3 @mouseenter="changebgcolor(index)" @mouseleave="clearcolor"> 如果h3還有同級標簽。可將鼠標移出的方法委派給父級標簽 <a href="">{{ one.categoryName }}</a> </h3> </div>
js
data() { return { bgcolor: -1, }; }, methods: { // 鼠標移動上更換背景色 changebgcolor(index) { // index:鼠標移上的元素的索引值 this.bgcolor = index; }, //鼠標移出,還原顏色 clearcolor(){ this.bgcolor = -1 } },
css
.cur { background-color: skyblue; }