Vue.js VueJS v-if=数组[索引]不工作

Vue.js VueJS v-if=数组[索引]不工作,vue.js,vuejs2,Vue.js,Vuejs2,我想制作一个组件,当鼠标悬停在图像上时,该组件将获取文本框 下面是HTML模板 <section class="item-container" v-for="(item, index) in items"> <div class="image-box" @mouseenter="changeStatus(index)"> <img class="image" src="item.link" alt> </div> <div

我想制作一个组件,当鼠标悬停在图像上时,该组件将获取文本框

下面是HTML模板

<section class="item-container" v-for="(item, index) in items">
  <div class="image-box" @mouseenter="changeStatus(index)">
    <img class="image" src="item.link" alt>
  </div>
  <div class="text-box" @mouseleave="changeStatus(index)" v-if="show[index]">
    <h4>{{ item.name }}</h4>
    <p>{{ item.content }}</p>
  </div>
</section>

当我执行上述代码时,我可以发现show属性已经更改。但是,v-if未更新。我们不能将数组[index]用于v-if吗?或者有其他原因吗?

问题不是关于
v-if
,这是因为Vue无法直接检测数组元素的变化,这是JavaScript的限制之一

因此,Vue为此提供了一些帮助函数,如
Vue.set

更改此
此。显示[索引]=!这个。显示[索引]

Vue.set(this.show,index,!this.show[index])

那么它应该会起作用

Vue.set
不是唯一的解决方案,如果您想知道,有几种方法可以实现这一点

您可以使用JavaScript数组的本机方法,Vue将钩住这些方法,以便能够检测更改

下面是使用
.splice

this.show.splice(索引,1,!this.show[index])

另一种方法是完全替换阵列。如果您使用的是ES6,则可以使用spread操作符轻松克隆阵列:

this.show[index] = !this.show[index]
this.show = [...this.show]
.map
也将起作用,因为它返回一个新数组

this.show = this.show.map((el, i) =>
  i === index ? !el : el
)

您可以使用JS对象而不是数组,并获得相同的效果。换句话说,将
show:[false,false,false],
替换为
show:{0:false,1:false,2:false},

在您可以使用的方法中的组件中:

this.$set(this.show, index, !this.show[index])

你反对在每个
项上使用布尔值而不是单独的
显示
数组吗?这很好,我仍然在看你列出的其他解决方案,但是。。vue.set不起作用。-示例:@robertotomás如果您使用的是Vue 1.0,则模板语法存在一些差异。在开发过程中也不要使用缩小的js,否则你看不到错误消息。我也遇到过同样的问题,这非常有用。非常感谢;)开关部分的Uisng Vue.set和created中的初始化都起作用。实际上,上述内容不正确。我只需将初始化更改为使用Vue.set,而不是changeStatus函数(或者在我的例子中是seeMe函数),非常感谢,我断断续续地处理这个问题已经6个月了,这对我来说很有意义,并且立即起到了作用,谢谢。不在这里工作,即使使用这种对象方法=(
this.$set(this.show, index, !this.show[index])