vue3 使用vuex Module

vuex官网关于module

根据官网安装vux

npm install vuex@next --save

新建store文件

目录结构
index.js

import { createStore } from 'vuex'
import {merge} from "lodash";
// Create a new store instance.
import bar from './bar';
import horizontal from "@/store/horizontal";
const store = createStore({
    modules: {
        bar:bar,
        horizontal:horizontal
    }
})
export default store;

bar.js

import {merge} from "lodash";

const bar = {
    namespaced: true,
    state() {
        return {
            options: {
                color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
                grid: {
                    left: '10%',
                    right: '10%',
                    top: '10%',
                    bottom: '10%'
                }

            },
        }
    },
    mutations: {
        // 设置options
        setOptions(state, options) {
            state.options = merge({}, state.options, options)
        },
    }
}
export default bar;

horizontal.js

import {merge} from "lodash";
const horizontal={
  namespaced: true,
    state() {
        return {
            options: {
                color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
                grid: {
                    left: '10%',
                    right: '10%',
                    top: '10%',
                    bottom: '10%'
                }

            },
        }
    },
    mutations: {
        // 设置options
        setOptions(state, options) {
            state.options = merge({}, state.options, options)
        },
    }
};

export default horizontal;

main.js

const app = createApp(App)
//引入router
import router from "./router";
app.use(router)

组件中使用

import {useStore} from "vuex";
const store=useStore();

// 获取state
//bar
let barLeft=store.state.bar.options.grid.left;
//horizontal
let horizontalLeft=store.state.horizontal.options.grid.left;

// mution
//horizontal
// horizontal/setOptions  horizontal:命名空间 setOptions:mutation处理函数名称
store.commit('horizontal/setOptions',options.value);

简单来说就是使用 namespaced: true,开启别名,state根据对象嵌套访问。
其他属性 加命名空间 。官网实例

 modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },
  }
}

你可能感兴趣的:(javascript,vue,vue.js)