第一章 VueX;
1.1 VueX是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
1.2 VueX的使用;、
- 安装
npm install vuex@next --save
- 创建
@/store/index文件
import Vue from 'vue'
import Vuex from 'vuex'
<!--引入的相关模块-->
import layout from "./modules/layout";
import bpmn from "./modules/bpmn";
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
layout,
bpmn
}
})
- 创建
@/store.modules文件夹
<!--在modules文件夹下创建一个.js文件-->
const state = {
menuList: [
{ lable: "导航四", value: "4", icon: "el-icon-setting" },
],
};
const mutations = {
UPDATEMENULIST(state, menuList) {
state.menuList = menuList;
},
};
const actions = {
updateMenuList(context, menuList) {
context.commit("UPDATEMENULIST", menuList);
}
};
export default {
namespaced: true,
state,
mutations,
actions
}
- 在
main.js中引入
import store from './store/index'
···
new Vue({
store,
render: h => h(App),
}).$mount('#app')
- 在组件中修改和使用
Vuex中的数据
使用数据:
方式一:可以直接在模板中使用
<MenuItemVue
:isCollapse="isCollapse"
:menuList="$store.state.layout.menuList"
></MenuItemVue>
方式二:通过计算属性来使用
computed: {
nodeVisible() {
return this.$store.state.bpmn.nodeVisible;
},
},
修改数据:
方式一:
handleClose() {
this.$store.commit("bpmn/TOGGLENODEVISIBLE", false);
},
方式二:
this.$store.dispatch("icon/getIconByUuid", name);
补充:vuex持久化处理,可以使用本地存储来解决;也可以用第三方插件 《vuex-persistedstate》