一、使用习惯1(模块化):
1、文件目录:
2、userStore.ts
import { Module } from 'vuex';
// import {setStorage,getStorage} from "../../util/common";
export default {
namespaced: true,
state: {
userInfo: { }
},
getters: {
// 类似计算属性,必需return
handleUserInfo: (state) => {
return state.userInfo.age = 20;
}
},
actions: {
// 异步过程,调用mutations中方法改变state
asyncUpdateUserInfo(store, newData) { // 第一个参数是vuex固定的参数,不需要手动去传递
store.commit("updateUserInfo", newData)
},
},
mutations: {
// 改变state
updateUserInfo(state, newData: { }) {
state.menuList = newData;
}
}
} as Module<any, any>;
3、vue文件中使用
(1)state(使用数据)
<template>{{ userInfo.name }}</template>
import { useStore } from 'vuex';
const store = useStore();
const { userInfo } = toRefs(store.state.userStore);
(2)mutations(常规改变数据状态)=> commit -> mutations
import { useStore } from "vuex"
const store = useStore()
const changeStoreUserInfo = () => {
store.commit("userStore/updateUserInfo", {name: '小明'})
}
(3)actions(异步改变数据状态)=> dispach -> mutations
import { useStore } from "vuex"
const store = useStore()
const asyncChangeStore = () => {
setTimeout(() => {
store.dispatch("userStore/asyncUpdateUserInfo", {name: '小李'})
}, 1000)
(4)getters(类似计算属性,需return)
如文件 2、userStore.ts 中 getters。
二、使用习惯2(无模块化):
文件目录
标签:const,vuex,vue3,userStore,state,使用,useStore,store From: https://www.cnblogs.com/suihung/p/17007758.html