[英]Vue.js How to toggle individual v-if divs inside a v-for loop?
我想为单击的v-for
循环中的每个帖子显示/隐藏下拉菜单:
<div v-for="(post, index) in posts" :key="index" >
<div v-on:click.prevent="toggleDropDown(post)">Show/hide menu
</div>
<div v-if="post.showDropDown">
<ul class="menu">
<li><a href="#" >Edit</a></li>
<li><a href="#" >Delete</a></li>
</ul>
</div>
<div>
{{post.body}}
</div>
</div>
和方法:
toggleDropDown(post) {
if (!post.showDropDown) {
post.showDropDown =true;
} else {
post.showDropDown =false;
}
},
但它不起作用。 单击“ Show/hide menu
时没有任何反应
请注意, posts
是从服务器获取的,并且post
对象没有showDropDown
字段。
而不是v-if="post.showDropDown"
我可以简单地使用"showDropDown=!showDropDown"
但是所有帖子上的所有菜单都一起打开/关闭,这不是故意的。
我该如何解决?
这可能是 Vue 反应性问题。 您可以尝试使用Vue.set
更改您的 html 代码以传递index
而不是post
<div v-on:click.prevent="toggleDropDown(index)">Show/hide menu
</div>
然后在javascript中
toggleDropDown(index) {
if (!this.posts[index].showDropDown) {
this.$set(this.posts[index], 'showDropDown', true)
} else {
this.$set(this.posts[index], 'showDropDown', false)
}
}
如果它不起作用,您可以尝试使用JSON.parse(JSON.stringify())
进行深度复制
toggleDropDown(index) {
this.posts[index].showDropDown = !this.posts[index].showDropDown
this.posts = JSON.parse(JSON.stringify(this.posts))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.