Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
1. 根目录下新建 vuex
目录,在 vuex
目录下创建 index.js
定义状态值
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
platform: '', //系统:android ios
statusBar: '', //状态栏高度
customBar: '', //自定义栏高度
},
mutations: {
setState: (state, obj) => {
console.log(state, obj)
state[obj.name] = obj.value;
},
setPlatform: (state, obj) => {
state.platform = obj;
},
setStatusBar: (state, obj) => {
state.statusBar = obj;
},
setCustomBar: (state, obj) => {
state.customBar = obj;
},
}
});
复制代码
2. 然后,在 main.js
挂载 Vuex
import store from './vuex'
Vue.prototype.$store = store
复制代码
3.最后,在页面引入
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['customBar', 'statusBar']),
},
methods: {
...mapMutations(['doIt'])
}
}
复制代码
vuex
里要设置的数据太多,懒得一个一个写,所以就这样写了一个方法setState
:
let colorList = [{},{}]
this.$store.commit('setState',{name:'colorList',value:this.colorList})
复制代码
mutations: {
setState: (state, obj) => {
console.log(state, obj)
state[obj.name] = obj.value;
},
}
复制代码
封装一下
export function setState(name,value) {
this.$store.commit('setState',{name:name,value:value})
}
this.setState('statusBar', this.StatusBar)
this.setState('customBar', this.CustomBar)
复制代码
正常写法:
this.$store.commit('setStatusBar',this.StatusBar)
this.$store.commit('setCustomBar',this.CustomBar)
复制代码
mutations: {
setStatusBar: (state, obj) => {
state.statusBar = obj;
},
setCustomBar: (state, obj) => {
state.customBar = obj;
},
}
复制代码