vuex modular writing method

Previously, all data and methods were written in an index.js file. As the project grows, more and more data needs to be stored. It is not easy to find all the data and methods in index.js, and some methods It might be super long, and it’s really uncomfortable to look at, so let’s start modularizing vuex.

 1. The first step is to create a new modules file under the store file and keep index.js.

 2. The second step is to use examples. Create auth.js and collapse.js under the modules file . These two js files are the modules we want to separate.

//auth.js
const authState = {
    namespaced: true, // 开启命名空间
    state: {
        count: 0,
    },
    mutations: {
        setCount(state, data) {
            state.count= data
        },
    },
    actions: {},
    getters: {
        count: state => state.count,
    }
}
export default authState 
//collapse.js
const collapse = {
    namespaced: true, // 开启命名空间
    state: {
        collapse: false,
    },
    mutations: {
        setCollapse(state, data) {
            state.collapse = data;
        },
    },
    actions: {},
    getters: {
        collapse: state => state.collapse,
    }
}

export default collapse

3. Introduce these two files into index.js

import {createStore} from 'vuex'
import collapse from "./modules/collapse";
import authState from './modules/auth';

export default createStore({
    modules: {
        collapse,
        authState 
    },
})

4. Used in the page

const store = useStore();

//获取值
const collapse = computed(() => {
    return store.getters['collapse/collapse']
});

const count= computed(() => {
    return store.getters['authState/count']
});

//设置值
store.commit('collapse/setCollapse', true)
store.commit('authState/setCount', 100)

The above is  how to write commit 

The following is the customary way to  write dispatch 

5. dispatch writing method

const collapse = {
    namespaced: true, // 开启命名空间
    state: {
        collapse: false,
    },
    mutations: {
        handleCollapse(state, data) {
            state.collapse = data;
        },
    },
    actions: {
         setHandleCollapse({commit}, data) {
            commit('handleCollapse', data)
         },
    },
    getters: {
        collapse: state => state.collapse
    }
}
export default collapse
//页面使用
store.dispatch('collapse/setHandleCollapse',true)

Guess you like

Origin blog.csdn.net/csdnyp/article/details/128215174