[英]Vue.js - Add or set new data to array in store
我有两个 Vue 组件,它们在商店中使用一个公共数组,如下所示:
var store = {
state: {
myArray: []
}
};
var FirstComp = Vue.extend({
template: '#first-template',
data: function () {
return {
arrayData: store.state.myArray
};
}
});
/* A second component quite identical */
我遵循了Vue js 指南中给出的示例。
我正在尝试使用来自另一个数组的新数据(在 ajax 调用之后)更新存储中数组中的数据,以便它影响两个组件。 我想要一种用新数组替换/连接旧数组的好方法。 我知道我不能像这样替换数组store.state.myArray = newArrayData;
因为我会失去 Vue 绑定。 但是文档中给出的方法(至少对于 concat)在商店的情况下不起作用(或者我可能遗漏了什么?)。
现在,我发现的唯一方法是根据操作使用带有push
、 $remove
或$set
的 foreach ,它不是那么优雅和实用。
例如,对于 concat,我这样做:
$.each(newArray, function (i, val) {
store.state.myArray.push(val);
});
但是更换它变得更丑陋。 什么是正确的方法?
(有关信息,我没有使用 Vuex 进行状态管理,我目前也不打算这样做,我保持非常简单)
为了使分配工作,您可以像这样在组件中使用“状态”:
var FirstComp = Vue.extend({
template: '#first-template',
data: function () {
return {
state: store.state
};
}
});
然后使用state.myArray
。 这样,如果您将执行store.state.myArray = newValue
它不会破坏绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.