Vue3中使用Vuex小记
sonder 大杯

最近在Vue3项目中使用Vuex和axios-mapper,与之前稍有不同,参考了Github的代码,在这里记录一下。

1
npm i vuex@next // 安装

创建一个store目录,创建一个ts文件来封装处理vuex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
* @Description: vuex 封装
* @Author: sonders
* @Date: 2021-12-09 17:31
*/
import { createStore } from 'vuex'
// 这里是因为ts中不能使用require(一直没有解决)
// 可以参考 https://vitejs.cn/guide/features.html#glob-import
const modulesFiles = import.meta.globEager('./modules/*.ts')
const modules: any = {}
for (const key in modulesFiles) {
const moduleName = key.replace(/^\.\/(.*)\.ts$/, '$1').replace('modules', '').replace('/', '')
const moduleContent = modulesFiles[key].default
modules[moduleName] = moduleContent
}

export default createStore({ modules })

创建一个modules自动注册模块 -》 在modules中随便创建一个.ts文件

1
2
3
4
5
6
export default {
namespaced: true,
state: {
aaa: "是的"
}
}

具体使用

1
2
3
4
5
6
import { useStore } from "vuex";
const dataStore = useStore();
const name = dataStore.state.data.aaa;
console.log(name);

// 也可以使用createNamespacedHelpers来指定模块,不太习惯,没有使用。
  • 本文标题:Vue3中使用Vuex小记
  • 本文作者:sonder
  • 创建时间:2021-12-09 17:40:23
  • 本文链接:https://sonderss.github.io/2021/12/09/Vue3中使用Vuex小记/
 评论