Reputation: 416
I have a component with data as:
export default {
data() {
return {
allItems: [],
orderItems: {},
itemAdded: [],
};
},
I want to access the itemAdded
array data which is present in the local component in the Vuex store.js
file.
Is there anyway to do so?
Upvotes: 0
Views: 418
Reputation: 6853
You can't access component data from vuex, what you can do is pass the data as the payload when dispatching a vuex action.
for example, your vuex action:
actions: {
doSomething(context, itemAdded) {
// Do something with itemAdded
}
}
and dispatch the action from your component:
this.$store.dispatch('doSomething', this.itemAdded);
If you want to change itemAdded
value on the component from the vuex action, you can return the value like this:
actions: {
doSomething(context, itemAdded) {
// Do something with itemAdded
return itemAdded;
}
}
and on your component:
// Need to use await since dispatch return a promise, you can also use `.then`
this.itemAdded = await this.$store.dispatch('doSomething', this.itemAdded);
Keep in mind that Vuex is a state management, and vuex action should do an action that's related to a state, not a place to store a 'reusable function'. I can't think of any case why would you want to return the edited value from the action, but if you think it makes sense / it's related to state, then you can do it this way.
Upvotes: 2