VUEX 狀態管理


VUEX 是VUE提供的一個狀態管理工具,具體他能做什么呢,比如有這樣的業務場景:

用戶在登錄后,可以設置他的登錄信息。去到用戶主頁,就可以顯示這個用戶的登錄信息。

其實就是用來在不同的組件之間共享信息。

我們使用 vue-element-admin 為例,來講解VUEX的使用。

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
})

export default store

構建store,這個store 支持模塊,在這個store中有三個模塊。

app 模塊定義

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方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM