B
B
bormor2018-08-14 12:00:02
Vue.js
bormor, 2018-08-14 12:00:02

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

1 answer(s)
0
0xD34F, 2018-08-14
@bormor

In products, replace the mutation with an action that will cause a mutation in cart. And from one module to directly change the state of another - the idea is so-so, in my opinion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question