Vuex 是一把雙刃劍。如果使用得當,使用 Vue 可以使你的工作更加輕松。如果不小心,它也會使你的代碼混亂不堪。
使用 Vuex 之前,你應該先了解四個主要概念:state、getter、mutation 和 action。一個簡單的 Vuex 狀態(tài)在 store 中的這些概念中操作數(shù)據(jù)。 Vuex 中的映射提供了一種從中檢索數(shù)據(jù)的好方法。
在文中,我將演示如何映射 Vuex 存儲中的數(shù)據(jù)。如果你熟悉 Vuex 基礎(chǔ),那么這些內(nèi)容將會幫你編寫更簡潔、更便于維護的代碼。
本文假設(shè)你了解 Vue.js 和 Vuex 的基礎(chǔ)知識。
Vuex 中的映射是什么?
Vuex 中的映射使你可以將 state 中的任何一種屬性(state、getter、mutation 和 action)綁定到組件中的計算屬性,并直接使用 state 中的數(shù)據(jù)。
下面是一個簡單的 Vuex store 例子,其中測試數(shù)據(jù)位于 state 中。
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { data: "test data" } })
如果要從 state 中訪問 data
的值,則可以在 Vue.js 組件中執(zhí)行以下操作。
computed: { getData(){ return this.$store.state.data } }
上面的代碼可以工作,但是隨著 state 數(shù)據(jù)量的開始增長,很快就會變得很難看。
例如:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { user: { id:1, age:23, role:user data:{ name:"user name", address:"user address" } }, services: {}, medical_requests: {}, appointments: {}, } } })
要從處于 state 中的用戶對象獲取用戶名:
computed: { getUserName(){ return this.$store.state.user.data.name } }
這樣可以完成工作,但是還有更好的方法。
映射 state
要將 state 映射到 Vue.js 組件中的計算屬性,可以運行以下命令。
import { mapGetters } from 'vuex'; export default{ computed: { ...mapState([ 'user', ]) } }
現(xiàn)在你可以訪問組件中的整個用戶對象。
你還可以做