vue3 学习--vuex4

4 篇文章 0 订阅

vuex4.0 的使用

  1. 创建index.ts
import { createStore } from "vuex";
import getters from "./getters";
import user from "./moudles/user";

export default createStore({
	modules: {
		user,
	},
	getters,
	// 启用严格模式,非mutation改变值都会报错
	strict: true,
});

  1. 创建getters.ts
const getters: any = {
	patientFrom: (state: any) => state.user.patientFrom,
	count: (state: any) => state.user.count,
};
export default getters;

  1. 创建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>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值