vuex4.0 的使用
- 创建index.ts
import { createStore } from "vuex";
import getters from "./getters";
import user from "./moudles/user";
export default createStore({
modules: {
user,
},
getters,
// 启用严格模式,非mutation改变值都会报错
strict: true,
});
- 创建getters.ts
const getters: any = {
patientFrom: (state: any) => state.user.patientFrom,
count: (state: any) => state.user.count,
};
export default getters;
- 创建moudles/user.ts
const user: any = {
state: {
patientFrom: {
name: "lsp",
},
count: 0,
},
mutations: {
SET_patientFrom: (state: any, patientFrom: object) => {
state.patientFrom = patientFrom;
},
SET_count: (state: any, count: number) => {
state.count = count;
},
},
actions: {
// 获取折线图数据
getComplexData({ commit }: any) {
return new Promise((resolve, reject) => {
commit("SET_patientFrom", { name: "nslsp" });
});
},
changeCount({ commit }: any, count: number) {
return new Promise((resolve, reject) => {
commit("SET_count", count);
});
},
},
};
export default user;
注意: 奈何本人没文化,写ts的时候一句any走天下,有大佬知道具体类型可以留言,感谢
以上是使用moudles的方式进行配置,可以无限增加模块,注意要及时导入到index.ts和getters.ts里面
使用方法
<template>
<div class="about">
<p>{{ c }}</p>
<el-button type="success" @click="changeCount">count++</el-button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, computed } from "vue";
import { useStore } from "vuex";
export default defineComponent({
name: "Home",
setup() {
const store = useStore();
const state: any = reactive({
count: 0,
});
const c = computed(() => store.getters.count);
console.log("22222", c.value); //0,1,2....
const changeCount = () => {
let a = ++state.count;
// store.dispatch("changeCount", a); //使用dispatch方式
store.commit("SET_count", a); //使用commit方式
};
return { changeCount, c };
},
});
</script>