Vuex 模块化

参考文档

  1. 文档1:https://blog.csdn.net/Dear_Mr/article/details/84576029
  2. 文档2:https://www.cnblogs.com/wangshucheng/p/vuex-006.html
    两篇都挺好的。

状态管理的使用

  1. 第一步-创建store-module.js
export default {
    // 增加命名空间
    namespaced: 'StoreModelBase',
    // 声明Vuex 的五个属性,其中state, mutations 是一定要定义的,其他的三个属性对象根据实际需要。
    // 初始化状态值--一定要有该属性对象    
    state() {
        return {
            MenuSwitchState: true
        }
    },
    // 自定义改变state初始值的方法--一定要有该属性对象
    mutations: {
    },
    // 状态计算属性--该属性对象不是必须的
    getters: {
        // 获取菜单栏开关
        getMenuSwitchState: state => {
            return state.MenuSwitchState;
        },
        test() {
            return "123";
        }
    },
    // 异步操作状态--该属性对象不是必须的
    actions: {
    },
    // 状态模块--该属性对象不是必须的
    modules: {
    }
}
  1. 创建store-moules.js(简单版)
// 引入Vue、和Vuex(固定写法)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

// model
import StoreModuleBase from './store-module-base'

// 导出
export default new Vuex.Store({
    modules: {  // 状态模块--该属性对象不是必须的
        StoreModuleBase
    }
})
  1. 创建store-moules.js(复杂版)
// 第一步:引入Vue、和Vuex(固定写法)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

// 第二步:声明Vuex 的五个属性,其中state, mutations 是一定要定义的,其他的三个属性对象根据实际需要。
// 初始化状态值--一定要有该属性对象
const state = {
}
// 自定义改变state初始值的方法--一定要有该属性对象
const mutations = {
}
// 状态计算属性--该属性对象不是必须的
const getters = {
}
// 异步操作状态--该属性对象不是必须的
const actions = {
}
// 状态模块--该属性对象不是必须的
const modules = {
    StoreModuleBase
}

// 第三步:创建一个 store 实例,将声明的五个变量赋值赋值给 store 实例,如下:
const store = new Vuex.Store({
    state,
    mutations,
    //下面三个非必须
    getters,
    actions,
    modules
})
// 第四步:导出 store 实例,供外部访问
export default store
  1. 在mail.js引入
import store from './store/store-modules'
// 实例化vue对象
let myVue = new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>'
})
  1. 在页面使用
  • 在js获取state的值(页面无需引入任何东西)
this.$store.state.StoreModuleBase.MenuSwitchState
  • 在页面获取(页面无需引入任何东西)
$store.state.StoreModuleBase.MenuSwitchState
  • 获取get里面的值(直接复制就可以获取到参数)
<script>
import { mapGetters } from "vuex";
export default {
  name: "MenuHead",
  props: {},
  data() {
    return {};
  },
  computed: {
    ...mapGetters("StoreModuleBase", ["getMenuSwitchState"])
  },
  created: function() {
    console.log("测试getter=", this.getMenuSwitchState);
  },
  onload: function() {},
  methods: {}
};
</script>
  • 向action里面设置值
    我还没写到这里,待补充

结尾

模块里面的方法,可以这么返回:

// 从state取值(获取菜单栏开关)
getMenuSwitchState: state => {
	return state.MenuSwitchState;
},
// 返回字符串
test() {
	return "123";
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值