store的結構:
city模塊:
在各模塊使用了命名空間的情況下,即 namespaced: true 時:
組件中訪問模塊里的state
傳統方法:
this.$store.state['模塊名']['屬性名']
例如:this.$store.state.city.list。
控制台輸出 this.$store.state
mapState方法:
import { mapState } from 'vuex' computed: { // ... ...mapState({ list: state => state.city.list }) }
組件中dispatch模塊里的actions
傳統方法:
// @params:opts Object or String this.$store.dispatch('模塊名/屬性名', opts)
組件中使用如:this.$store.dispatch('city/add', '上海')
mapActions方法:
引入:import { mapActions } from 'vuex'
methods中的屬性名可以更改成其他任意名字,但是屬性值需要和模塊名,actions屬性名對應。
在組件中訪問模塊里的getter
傳統方法:
this.$store.getters['模塊名/屬性名']
如:this.$store.getters['city/findOne']('a')
mapGetters方法:
引入:import { mapGetters } from 'vuex'
這個getter返回的是一個函數,這樣可以給getter傳參。此時getter通過方法訪問時,每次都會去進行調用,而不會緩存結果。
而getter 在通過屬性訪問時是作為 Vue 的響應式系統的一部分緩存其中的。
轉自:https://www.cnblogs.com/caimuguodexiaohongmao/p/11854228.html