Answer the question
In order to leave comments, you need to log in
Vuex modules - how to pass data from one module to another?
The classic task is a product catalog and a shopping cart.
It is necessary to transfer an item from the catalog to the basket.
How to access state from cart module in product catalog module?
(I use the default option - with a global namespace)
(tried through state and through rootState - does not work yet)
// ../store/module/products.js
export default {
state: {
items: [
{title: 'Product 1', id: 1},
{title: 'Product 2', id: 2},
{title: 'Product 3', id: 3},
{title: 'Product 4', id: 4},
]
},
mutations: {
addProductToCart(state, id, rootState) {
rootState.cart.cartItems.push({title:'NEW ITEM', id:5})
}
},
};
// ../store/module/cart.js
export default {
state: {
cartItems: [
{title: 'Product 1', id: 1},
{title: 'Product 2', id: 2},
]
}
};
// ../store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import products from './modules/products';
import cart from './modules/cart';
Vue.use(Vuex);
export default new Vuex.Store({
modules:{
products,
cart
}
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question