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