我正在尝试学习 vue,但我很难让它在单击后通过数组运行。
数组首先是空的,但是当单击按钮时,这将调用一个方法来用数据填充数组。我正在使用 v-for 遍历数组,但看起来它只在调用方法之前遍历数组。如何在事件发生后使其成为 v-for 绑定(bind)?
该方法之所以有效,是因为它在控制台中显示了新数组中的数据。
<button @click="updateList">Update List</button>
<li v-if="clicked" v-for="item in newList">
{{ item }}
</li>
<script>
var vm = new Vue({
el: '#app',
data: {
clicked: false,
list: ["one","two","three"],
newList: []
},
methods: {updateList: function (){
for (i=0;i<this.newList.length;i++) {
this.newList[i] = "you are" + this.list[i];
}
this.clicked = true;
}
}
})
也许忽略上面片段中的语法。
最佳答案
v-if
和 v-for
应该在不同的元素中。根据 Vue 官方文档:
Using v-if and v-for together is not recommended. When used together with v-if, v-for has a higher priority than v-if.
<button @click="updateList">Update List</button>
<ul v-if="clicked">
<li v-for="item in newList">
{{ item }}
</li>
</ul>
有关详细信息,请参阅 v-if
vs v-for
.
关于javascript - 单击后如何使 v-for 再次更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193809/