根据官网安装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')
},
}
}
本文介绍了如何在 Vuex 中设置和使用模块(module),通过 `namespaced: true` 开启命名空间,使得状态管理和突变在不同模块间隔离。在 `index.js` 中导入并注册模块,如 `bar` 和 `horizontal`,每个模块包含其自身的状态、突变和命名空间。在组件中,可以利用 `useStore` 获取 store 并通过命名空间访问和修改状态,如 `store.state.bar.options.grid.left` 和 `store.commit('horizontal/setOptions', options.value)`。此示例展示了 Vuex 模块化组织和操作状态的方式。
3万+

被折叠的 条评论
为什么被折叠?



