javascript Vuejs 和 Vue.set(),更新一个 Key/Value 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48809248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vuejs and Vue.set(), update an Key/Value array
提问by smooth_smoothie
I am trying to figure out how the this.$set (aka Vue.set)api works when using it to update an multidimensional array.
我试图弄清楚this.$set (aka Vue.set)在使用它更新多维数组时 api是如何工作的。
Given:
鉴于:
new Vue({
el: '#app',
data: {
rows:[{"id": "4", "edit": "true" }, { "id": "5", "edit": "false" }]
},
....
How will I use $this.setto do something like this:
我将如何$this.set用来做这样的事情:
this.rows[0].edit = false
I know this doesn't work:
我知道这不起作用:
this.$set(this.rows2, 0, false)
What is the correct way to use $this.set for a KV pair array ?
将 $this.set 用于 KV 对数组的正确方法是什么?
回答by thanksd
Since the editproperties in your rowsobjects are already set, you do not need to use Vue.setin this case. You can just set the property value and Vue will notice the change:
由于edit您的rows对象中的属性已经设置,因此您不需要Vue.set在这种情况下使用。你可以只设置属性值,Vue 会注意到变化:
this.rows[0].edit = false;
Here's a simple example:
这是一个简单的例子:
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>
However, if the editproperty of your row objects were not set initially (or if you just wanted to be safe), then you would need to use Vue.setin order to add the property and have it be reactive:
但是,如果edit您的行对象的属性最初没有设置(或者如果您只是想安全),那么您需要使用Vue.set以添加该属性并使其具有反应性:
this.$set(this.rows[0], 'edit', false);
Here's an example of that case:
下面是这种情况的一个例子:
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>

