需求如下:三个盒子,click改变图片、文字颜色、背景颜色。hover改变图片和文字颜色,两个事件的两张图片是不一样的。 其中click点击之后下面展示不同内容。
思路:data里的每个数据都有绑定一个id。
click绑定事件, @click="clickHandle(item.id)",给一个变量等于当前的元素的id来控制color,background-color,img。点击展示不同内容可以用v-if="isChecked == 0" v-else-if="isChecked == 1"来控制。
vue里没有hover事件,用mouseenter,mouseleave来模拟,@mouseenter="isHover = item.id", @mouseleave="isHover = -1"。再写一个变量等于当前的元素的id来控制img地址的变化。hover改变文字颜色可以用css来控制li:hover {color: #dc2828;}。
比较复杂的是img,需要用两次双目表达式,先判断是否是是click状态,再判断是否是hover状态。
data和methods:
data() {
return {
listData: [
{
id: 0,
name: 'iphone',
icon1: require('assets/images/icom_pingguo1.png'),
icon2: require('assets/images/icom_pingguo2.png'),
icon3: require('assets/images/icom_pingguo3.png'),
},
{
id: 1,
name: 'Android',
icon1: require('assets/images/icom_anzhuo1.png'),
icon2: require('assets/images/icom_anzhuo2.png'),
icon3: require('assets/images/icom_anzhuo3.png'),
},
{
id: 2,
name: 'Windows',
icon1: require('assets/images/icom_windows1.png'),
icon2: require('assets/images/icom_windows2.png'),
icon3: require('assets/images/icom_windows3.png'),
},
],
isChecked: 0,
isHover: 0,
}
},
methods: {
clickHandle(val) {
this.isChecked = val
},
},
html:
<ul>
<li
v-for="item in listData"
:key="item.id"
@click="clickHandle(item.id)"
@mouseenter="isHover = item.id"
@mouseleave="isHover = -1"
:style="item.id == isChecked ? 'color:#dc2828' : ''"
>
<div :class="item.id == isChecked ? 'down-icon-active' : 'down-icon'">
<img
:src="
item.id == isChecked
? item.icon2
: item.id == isHover
? item.icon3
: item.icon1
"
alt=""
/>
</div>
<div class="down-text">{{ item.name }}</div>
</li>
</ul>
<div id="type-detail" v-if="isChecked == 0">
内容0
</div>
<div id="type-detail" v-else-if="isChecked == 1">
内容1
</div>
<div id="type-detail" v-else-if="isChecked == 2">
内容2
</div>
css:
.down-icon,.down-icon-active {
height: 100px;
width: 100px;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
img {
width: 39px;
}
}
.down-icon{
background-color: #fafafa;
}
.down-icon-active {
background-color: #dc2828;
}
li:hover {
cursor: pointer;
color: #dc2828;
}