Vuejs和Vue.set(),更新Key / Value数组 [英] Vuejs and Vue.set(), update an Key/Value array
问题描述
我试图找出这个。$ set(又名Vue.set)
api在使用它来更新多维数组时的效果。
I am trying to figure out how the this.$set (aka Vue.set)
api works when using it to update an multidimensional array.
鉴于:
new Vue({
el: '#app',
data: {
rows:[{"id": "4", "edit": "true" }, { "id": "5", "edit": "false" }]
},
....
将如何我使用 $ this.set
来做这样的事情:
How will I use $this.set
to do something like this:
this.rows[0].edit = false
我知道这不起作用:
this.$set(this.rows2, 0, false)
对于KV对阵列使用$ this.set的正确方法是什么?
What is the correct way to use $this.set for a KV pair array ?
推荐答案
由于行
对象中的编辑
属性已设置,因此您无需使用 Vue.set
在这种情况下。您可以设置属性值,Vue会注意到更改:
Since the edit
properties in your rows
objects are already set, you do not need to use Vue.set
in this case. You can just set the property value and Vue will notice the change:
this.rows[0].edit = false;
这是一个简单的例子:
new Vue({
el: '#app',
data() {
return {
rows:[
{ "id": "4", "edit": true },
{ "id": "5", "edit": false }
],
}
},
methods: {
editNext() {
let index = this.rows.findIndex(r => r.edit);
this.rows[index].edit = false;
let next = ++index % this.rows.length;
this.rows[next].edit = true;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<div v-for="(row, i) in rows" v-if="rows[i].edit">
Editing Row ID {{ row.id }}
</div>
<button @click="editNext">Edit Next</button>
</div>
但是,如果最初没有设置行对象的 edit
属性(或者如果你只是想保持安全),那么你需要使用 Vue.set
来添加属性并让它被激活:
However, if the edit
property of your row objects were not set initially (or if you just wanted to be safe), then you would need to use Vue.set
in order to add the property and have it be reactive:
this.$set(this.rows[0], 'edit', false);
这是一个例子:
new Vue({
el: '#app',
data() {
return {
rows:[
{ "id": "4", "edit": true },
{ "id": "5" }
],
}
},
methods: {
editNext() {
let i = this.rows.findIndex(r => r.edit);
this.$set(this.rows[i], 'edit', false);
let next = ++i % this.rows.length;
this.$set(this.rows[next], 'edit', true);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<div v-for="row in rows" v-if="row.edit">
Editing Row ID {{ row.id }}
</div>
<button @click="editNext">Edit Next</button>
</div>
这篇关于Vuejs和Vue.set(),更新Key / Value数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!