我正在尝试更改鼠标/mouseleave事件中v-for循环中的单个元素的类悬停的元素变化。
我尝试将类绑定到变量,但这显然会导致列表中的所有元素更改。
<template>
<ul>
<li class="item" v-for="item in items" @mouseenter="showInfoBar()" @mouseleave="hideInfoBar()">
<span class="infobar" :class="{ show : infoBar }"> </span>
</li>
</ul>
</template>
<script>
export default {
name: 'ItemsList',
props: ['items'],
data() {
return {
infoBar: false
}
},
methods: {
showInfoBar() {
this.infoBar = true
},
hideInfoBar() {
this.infoBar = false
}
}
}
</script>
您可以使用此而是
<template>
<ul>
<li class="item" v-for="(item, index) in items" :key="index" @mouseenter="infoBar = index" @mouseleave="infoBar = null">
<span class="infobar" :class="{ show : infoBar == index }"> </span>
</li>
</ul>
</template>
然后,对于您的数据属性, data() {
return {
infoBar: null
}
},
问题在于,当应该独立控制它们时,您的infoBar
代表所有信息栏的状态。
将infoBar
变成数组,每个元素代表该索引处的信息栏的状态应解决您的问题。
<template>
<ul>
<li class="item" v-for="(item, index) in items" @mouseenter="showInfoBar(index)" @mouseleave="hideInfoBar(index)">
<span class="infobar" :class="{ show : infoBar[index] }"> </span>
</li>
</ul>
</template>
<script>
export default {
name: 'ItemsList',
props: ['items'],
data() {
return {
infoBar: []
}
},
mounted: function() {
for(var i = 0; i < this.items.length; i++) {
this.infoBar.push(false);
}
},
methods: {
showInfoBar(index) {
this.infoBar[index] = true;
},
hideInfoBar(index) {
this.infoBar[index] = false;
}
}
}
</script>
我认为,我的意思是,更好的方法应该以分离的组件来处理它,我的意思是,将每个组件的状态留给每个组件而不是,而不是处理"组成部分"集合的状态。在一个数组中,我是基于这个想法的反应,您可以将ItemsList
和Item
声明为不同的组件,然后对于每个项目,一个单独的状态,请告诉我,如果您理解这种方法,祝您好运。
阅读代码
后我也认为,一旦您重构代码,而不是以两种不同的方法来处理状态,而只需声明 toggleMethod()
并对您目前正在查看的状态的当前值进行逻辑拒绝。
这更好:
function toggleState() {
this.someState = !this.someState;
}
比这个
function showState() {
this.someState = true;
}
function hideState() {
this.someState = false;
}
祝你好运。