vue3使用vuex的示例(模块化功能)

目录

1. store/index.ts

2. main.ts

3. App.vue调用

4. 如果删除moduleA的namespaced属性, 保留moduleB的namespaced:true

5. 则App.vue修改为:


1. store/index.ts

注意: 需要使用时带上模块名称的namespaced必须为true, 不写或者为false时调用时不需要写模块名称(获取state的值必须加模块名)

import { createStore } from "vuex";
// A模块
const moduleA = {
  namespaced: true,
  state: {
    name: "moduleA",
  },
  getters: {
    newName(state) {
      return state.name;
    },
  },
  mutations: {
    changeName(state, payload) {
      state.name = payload;
    },
    updateAge(state, playLoad) {
      state.age = playLoad;
    },
  },
  actions: {
    changeAge({ commit }, age) {
      setTimeout(() => {
        commit("updateAge", age);
      }, 0);
    },
  },
};
// B模块
const moduleB = {
  namespaced: true,
  state: {
    name: "moduleB",
    age: 33,
  },
  getters: {
    newName(state) {
      return state.name;
    },
  },
  mutations: {
    changeName(state, payload) {
      state.name = payload;
    },
    updateAge(state, playLoad) {
      console.log("playLoad", playLoad);
      state.age = playLoad;
    },
  },
  actions: {
    changeAge(ctx, count) {
      console.log("触发了-模块B的action");
      setTimeout(() => {
        ctx.commit("updateAge", count);
      }, 1000);
    },
  },
};
export default createStore({
  // 分模块
  modules: {
    moduleA,
    moduleB,
  },
});

2. main.ts

import { createApp } from "vue";
import App from "./App.vue";
import * as Vue from "vue";
import store from './store';

const app = createApp(App);
app.use(store);
app.mount("#app");

3. App.vue调用




4. 如果删除moduleA的namespaced属性, 保留moduleB的namespaced:true

import { createStore } from "vuex";
// A模块
const moduleA = {
  state: {
    name: "moduleA",
  },
  getters: {
    newName(state) {
      return state.name;
    },
  },
  mutations: {
    changeName(state, payload) {
      state.name = payload;
    },
    updateAge(state, playLoad) {
      state.age = playLoad;
    },
  },
  actions: {
    changeAge({ commit }, age) {
      setTimeout(() => {
        commit("updateAge", age);
      }, 0);
    },
  },
};
// B模块
const moduleB = {
  namespaced: true,
  state: {
    name: "moduleB",
    age: 33,
  },
  getters: {
    newName(state) {
      return state.name;
    },
  },
  mutations: {
    // 更改数据函数
    changeName(state, payload) {
      state.name = payload;
    },
    updateAge(state, playLoad) {
      console.log("playLoad", playLoad);
      state.age = playLoad;
    },
  },
  actions: {
    changeAge(ctx, count) {
      setTimeout(() => {
        ctx.commit("updateAge", count);
      }, 1000);
    },
  },
};
export default createStore({
  // 分模块
  modules: {
    moduleA,
    moduleB,
  },
});

5. 则App.vue修改为:




你可能感兴趣的:(JavaScript面试问题,vue,vuex,vue.js,javascript,前端)