在开源版本的 mar3d-vue-project 项目中如何集成自己的vuex状态管理呢?这里我来介绍两种方式
方式一:
这个项目中已经帮我们引入了vuex,可以在每个页面中直接使用,以example为例,下图可以看到页面目录下存在一个widget-store.js 的文件,本文件可以直接编写vuex相关代码
interface State extends WidgetState {count: number}const store: StoreOptions<State> = {state: {widgets: [],openAtStart: [],count: 1},getter: {},mutations: {updateCount(state) {state.count ++}},actions: {}}
以上方法虽然方便,但是和项目内部状态使用了同一个命名空间,所以第二种方式,就是创建一个自己单独的vuex命名空间
方式二:
在 src/common/store下创建自己的vuex配置,如 my-store.ts
// my-store.tsimport { InjectionKey } from 'vue'import { createStore, Store } from 'vuex'// 为 store state 声明类型export interface State {count: number}// 定义 injection keyexport const key: InjectionKey<Store<State>> = Symbol("my-store")export const myStore = createStore<State>({state: {count: 0},getter: {},mutations: {updateCount(state) {state.count ++}},actions: {}})
然后在main.ts中注册
// main.tsimport { myStore, key as myKey /* 取一个别名,防止变量冲突 */ } from "@/common/store/my-store.js"app.use(myStore, myKey)
使用时只需要通过自己的命名空间标识 key 来获取store对象就可以了
import { useStore } from 'vuex'import { key } from './store'const store = useStore(key)
以上就是在 mars3d基础项目中使用vuex的简单演示,大家可以根据自己项目的具体需求灵活选择
