简体   繁体   English

Vue.js - 向存储中的数组添加或设置新数据

[英]Vue.js - Add or set new data to array in store

I have two Vue components that use a common array set in a store like this:我有两个 Vue 组件,它们在商店中使用一个公共数组,如下所示:

var store = {
    state: {
        myArray: []
    }
};

var FirstComp = Vue.extend({
    template: '#first-template',
    data: function () {
        return {
            arrayData: store.state.myArray
        };
    }
});

/* A second component quite identical */

I followed the example given in the Vue js guide .我遵循了Vue js 指南中给出的示例。

I'm trying to update the data in the array in the store with new data from another array (after an ajax call), so that it impacts both components.我正在尝试使用来自另一个数组的新数据(在 ajax 调用之后)更新存储中数组中的数据,以便它影响两个组件。 I would like to have a nice way of replacing / concating the old array with a new one.我想要一种用新数组替换/连接旧数组的好方法。 I know I can't just replace the array like this store.state.myArray = newArrayData;我知道我不能像这样替换数组store.state.myArray = newArrayData; because I would loose the Vue binding.因为我会失去 Vue 绑定。 But the method given in the docs (at least for concat) doesn't work in the case of the store (or maybe I'm missing something?).但是文档中给出的方法(至少对于 concat)在商店的情况下不起作用(或者我可能遗漏了什么?)。

Right now, the only way I've found is to use a foreach with push , $remove or $set depending on the operation and it is not that elegant and practical.现在,我发现的唯一方法是根据操作使用带有push$remove$set的 foreach ,它不是那么优雅和实用。

For example, for concat, I do this:例如,对于 concat,我这样做:

$.each(newArray, function (i, val) {
    store.state.myArray.push(val);
});

But for replacing it gets uglier.但是更换它变得更丑陋。 What would be the proper way to this?什么是正确的方法?

(For info, I'm not using Vuex for state management and I don't plan to at the moment, I'm keeping it very simple) (有关信息,我没有使用 Vuex 进行状态管理,我目前也不打算这样做,我保持非常简单)

To make the assignment work you can just use "state" in your component like this:为了使分配工作,您可以像这样在组件中使用“状态”:

var FirstComp = Vue.extend({
    template: '#first-template',
    data: function () {
        return {
            state: store.state
        };
    }
});

And then use state.myArray .然后使用state.myArray This way if you will do store.state.myArray = newValue it won't break the binding.这样,如果您将执行store.state.myArray = newValue它不会破坏绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM