参考文档
- 文档1:https://blog.csdn.net/Dear_Mr/article/details/84576029
- 文档2:https://www.cnblogs.com/wangshucheng/p/vuex-006.html
两篇都挺好的。
状态管理的使用
- 第一步-创建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: {
}
}
- 创建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
}
})
- 创建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
- 在mail.js引入
import store from './store/store-modules'
// 实例化vue对象
let myVue = new Vue({
el: '#app',
store,
router,
components: { App },
template: '<App/>'
})
- 在页面使用
- 在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";
}