Vuex模块化

创建命名空间

mian.js

import Vue from "vue";
import store from "./store";

new Vue({
  el: "#BYUI_APP",
  router,
  store,
  render: (h) => h(App),
});

src/store/index.js

import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";

Vue.use(Vuex);
const modulesFiles = require.context("./modules", true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});
const store = new Vuex.Store({ modules, getters });
export default store;

src/store/getters.js

const getters = {
	// testVuexModules: 对应命名空间的模块名
  phone: (state) => state.testVuexModules.phone,
  address: (state) => state.testVuexModules.address,
  // arrList(名字自取): "testVuexModules"模块的映射集,方便获取state的值
  arrList:(state) => {
    return state.testVuexModules
  },
};
export default getters;

src/store/modules 各自管理仓库

在这里插入图片描述

src/store/modules/testVuexModules.js 命名空间模块

 const state = {
  address: '',
  phone: '',
};

const mutations = {
  CHANGE_INFO: (state, info) => {
      state.address = info.address;
      state.phone = info.phone;
      // 如果想状态不想因为浏览器刷新而丢失,可以将状态缓存到本地
      // localStorage(数据永久缓存在本地浏览器中)   sessionStorage(临时缓存,有时效)
      //  两者使用方式一致,区别在时效
      localStorage.setItem("GET_PHONE", state.phone)
      // 移除缓存
      localStorage.removeItem('GET_PHONE')
  },
};

const actions = {
  changeInfo({ commit }, info) {
    commit("CHANGE_INFO", info);
  },
};
// 添加namespaced:true的方式使其成为带命名空间的模块
export default { namespaced: true, state, mutations, actions };

组件内提交与获取Vuex的值:

1.异步操作 this.$store.dispatch

//提交数据: testVuexModules:模块名, changeInfo: action方法名
this.$store.dispatch("testVuexModules/changeInfo", this.form)

//获取状态方式 1:对应getters.js的getters对象
this.$store.getters.address

//获取状态方式 2:当需要获取多个state状态,可以通过映射集,减少代码量,增加美观性
//辅助函数mapGetters批量使用状态, arrList: 对应getters.js的属性arrList
import { mapGetters, mapState } from "vuex"
// computed 
computed: {
    ...mapGetters(["arrList"]),
},
 
// 获取数据  
this.arrList.phone

2.同步操作 this.$store.commit

// 提交数据: testVuexModules(模块名), CHANGE_INFO(mutations方法名)
// 注意: 此提交方式需在 namespaced 开启 true 才会生效
this.$store.commit("testVuexModules/CHANGE_INFO", this.form)

// 获取状态方式 1
this.$store.state.testVuexModules.phone

// 获取状态方式 2
import { mapGetters, mapState } from "vuex"

// computed
computed: {
   ...mapGetters(["arrList"]),
    ...mapState({
      getMapState: (state) => state.testVuexModules,
    }),
},

// 获取数据
this.getMapState.phone

获取缓存的值

localStorage.getItem("GET_PHONE")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值