Vue 狀態管理模式 -- Vuex

這是我參與更文挑戰的第4天,活動詳情查看: 更文挑戰vue

Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化ios

本章講解 Vue 項目中 Vuex 的具體使用vuex

先在項目目錄下創建一個 store 文件夾,而且在下面創建一個 index.js 文件axios

image.png

// index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
複製代碼

在 Vue 實例上掛載 store數組

// main.js
import store from '@/store'

new Vue({
  el: '#app',
  store
})
複製代碼

在全局去使用store,在組件裏就能夠經過 this.$store.state.data 全局調用緩存

建立 modules

當應用比較很是複雜時,Vuex 容許咱們將 store 分割成模塊(module)。每一個模塊擁有本身的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行一樣方式的分割markdown

例:modules / user 模塊app

image.png

每一個狀態集最後合成到index.js中異步

image.png

模塊中的 state、getters、mutations、actionsasync

state

const state = {
  pool_list_data: '',
  pool_id_list: [],
  current_pools: {
    poolId: "CIDC-RP-25",
    poolName: "華東-蘇州",
  },
}

this.$store.state.user.pool_list_data
複製代碼

經過 store.state 來獲取狀態對象,以及經過 store.commit 方法觸發狀態變動

Vuex 的狀態存儲是響應式的。當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那麼相應的組件也會相應地獲得高效更新

不能直接改變 store 中的狀態。改變 store 中的狀態的惟一途徑就是顯式地提交 (commit) mutation。這樣使得咱們能夠方便地跟蹤每個狀態的變化,從而讓咱們可以實現一些工具幫助咱們更好地瞭解咱們的應用

因爲 store 中的狀態是響應式的,在組件中調用 store 中的狀態簡單到僅須要在計算屬性中返回便可。觸發變化也僅僅是在組件的 methods 中提交 mutation

getters

const getters = {
  doneTodos: state => {
    return state.todos.filter(todo => todo.done)
  }
  pool_list_data: state => state.pool_list_data,
  pool_id_list: state => state.pool_id_list,
  current_pools: state => state.current_pools,
}

store.getters["user/doneTodos"]
複製代碼

getter能夠認爲是 store 的計算屬性,就像計算屬性同樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被從新計算

也能夠經過讓 getter 返回一個函數,來實現給 getter 傳參。在你對 store 裏的數組進行查詢時很是有用

注意:getter 在經過方法訪問時,每次都會去進行調用,而不會緩存結果

mapGetters

mport { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用對象展開運算符將 getter 混入 computed 對象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // 使用對象形式,能夠給 getter 屬性另取一個名字
      // doneCount: 'doneTodosCount'
    ])
  }
}
複製代碼

mapGetters 輔助函數僅僅是將 store 中的 getter 映射到局部計算屬性

mutations

更改 Vuex 的 store 中的狀態的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似於事件:每一個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是咱們實際進行狀態更改的地方,而且它會接受 state 做爲第一個參數

你能夠向 store.commit 傳入額外的參數,即 mutation 的 載荷(payload)

const mutations = {
  'SET_POOL_INFO'(state, pooldata) {
    state.pool_list_data = pooldata
    state.pool_id_list = []
    pooldata.forEach((i) => {
      state.pool_id_list.push(i.poolId)
    })
  },
  'SET_CURRENT_POOLS'(state, region_data) {
    state.current_pools.poolId = region_data.value
    state.current_pools.poolName = region_data.name
  }
}

commit('SET_CURRENT_POOLS', region_data)
複製代碼

actions

Action 相似於 mutation,不一樣在於:

  • Action 提交的是 mutation,而不是直接變動狀態
  • Action 能夠包含任意異步操做
const actions = {
  async getInfo({ commit }) {
    return new Promise(async (resolve, reject) => {
      commit('SET_ROLES', ['Admin'])
      axios.defaults.headers.common["pool-Id"] = state.current_pools.poolId
      const user = await getUserInfo({ user_id: state.user_id })
      if (user.status == 200) {
        commit('SET_ECLOUD_USER', user.data)
      }
      resolve(state.roles)
    })
  },
}

// Action 經過 store.dispatch 方法觸發,一樣支持載荷方式和對象方式進行分發
this.$store.dispatch('user/getInfo')
複製代碼

mapActions

在組件中使用 this.$store.dispatch('xxx') 分發 action,或者使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用

mport { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'user/getInfo', 
      // 將 this.increment() 映射爲 this.$store.dispatch('user/getInfo')
      // mapActions 也支持載荷,及對象形式
    ]),
  }
}
複製代碼
相關文章
相關標籤/搜索