MrSunOcean 2020-01-03
VUEX 是VUE提供的一个状态管理工具,具体他能做什么呢,比如有这样的业务场景:
用户在登录后,可以设置他的登录信息。去到用户主页,就可以显示这个用户的登录信息。
其实就是用来在不同的组件之间共享信息。
我们使用 vue-element-admin 为例,来讲解VUEX的使用。
//store/index.js
import Vue from ‘vue‘
import Vuex from ‘vuex‘
import getters from ‘./getters‘
import app from ‘./modules/app‘
import settings from ‘./modules/settings‘
import user from ‘./modules/user‘
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
settings,
user
},
getters,
plugins:[
]
})
export default store构建store,这个store 支持模块,在这个store中有三个模块。
app 模块定义
//modules/app.js
import Cookies from ‘js-cookie‘
const state = {
sidebar: {
opened: Cookies.get(‘sidebarStatus‘) ? !!+Cookies.get(‘sidebarStatus‘) : true,
withoutAnimation: false
},
device: ‘desktop‘
}
const mutations = {
TOGGLE_SIDEBAR: state => {
state.sidebar.opened = !state.sidebar.opened
state.sidebar.withoutAnimation = false
if (state.sidebar.opened) {
Cookies.set(‘sidebarStatus‘, 1)
} else {
Cookies.set(‘sidebarStatus‘, 0)
}
},
CLOSE_SIDEBAR: (state, withoutAnimation) => {
Cookies.set(‘sidebarStatus‘, 0)
state.sidebar.opened = false
state.sidebar.withoutAnimation = withoutAnimation
},
TOGGLE_DEVICE: (state, device) => {
state.device = device
}
}
const actions = {
toggleSideBar({ commit }) {
commit(‘TOGGLE_SIDEBAR‘)
},
closeSideBar({ commit }, { withoutAnimation }) {
commit(‘CLOSE_SIDEBAR‘, withoutAnimation)
},
toggleDevice({ commit }, device) {
commit(‘TOGGLE_DEVICE‘, device)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}actions: 就是提供给外部调用。
state: 就是app定义的状态
namespaced:支持命名空间
toggleSideBar() {
this.$store.dispatch(‘app/toggleSideBar‘)
}可以通过 this.$store.dispatch 触发action方法。