2

I have two Vue components that use a common array set in a store like this:

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.

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. 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;because I would loose the Vue binding. 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?).

Right now, the only way I've found is to use a foreach with push, $removeor $set depending on the operation and it is not that elegant and practical.

For example, for concat, I do this:

$.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)

1 Answer 1

1

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. This way if you will do store.state.myArray = newValue it won't break the binding.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It's working perfectly! I knew I was missing something quite obvious, but couldn't figure out what, now I understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.