Vue3.x下使用VueX4.x

创建Store-Vuex4.x

Vue3.x下使用VueX4.x_第1张图片

store—>modules—>user.ts

import { Module } from 'vuex';
interface StoreUser {
  accountName: string;
}
const userModule = {
  namespaced: true,
  state() {
    const a = localStorage.getItem('accountName');
    return {
      accountName: a,
    };
  },
  mutations: {
    setText(state: StoreUser, payload: any) {
      console.log('修改成功');
      state.accountName = payload.text;
      localStorage.setItem('accountName', state.accountName);
    },
  },
  actions: {
    setText(context, payload: any) {
      context.commit('setText', payload);
    },
  },
  getters: {
    getText(state: StoreUser) {
      return state.accountName;
    },
  },
};

export default userModule;

store—>index.ts

import { createStore } from 'vuex';

import a from './modules/module-a';
import user from './modules/user';

export default createStore({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    a,
    user,
  },
});

获取以及使用

import { useStore } from 'vuex';
const store = useStore();
let getText = computed(() => {
  return store.getters['user/getText'];
});
console.log(getText);


Vue3.x下使用VueX4.x_第2张图片

你可能感兴趣的:(Vue3,ue4,typescript,javascript)