vuex状态管理
VUEX 状态管理
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方法。
相关推荐
  CSCCockroach    2020-09-15  
   lbPro0    2020-07-05  
   MrSunOcean    2020-06-21  
   lylwanan    2020-06-14  
   Callmesmallpure    2020-05-31  
   ShaLiWa    2020-05-25  
   墨龙吟    2020-04-24  
   MrSunOcean    2020-04-24  
   H女王范儿    2020-04-22  
   lbPro0    2020-04-16  
   ShaLiWa    2020-02-29  
   ShaLiWa    2020-01-17  
   lbPro0    2020-01-01  
   H女王范儿    2019-12-29  
   MrSunOcean    2019-12-27