Vuex
就是提供一個倉庫,
Store
倉庫裡面放了很多對象。其中state就是資料源存放地,對應于與一般
Vue
對象裡面的
data
(後面講到的
actions
和
mutations
對應于
methods
)。
在使用
Vuex
的時候通常會建立
Store
執行個體
new Vuex.store({state,getters,mutations,actions})
有很多子子產品的時候還會使用到modules
在元件中分發 Action
你在元件中使用
this.$store.dispatch('xxx')
分發 action,或者使用
mapActions
輔助函數将元件的 methods 映射為
store.dispatch
調用(需要先在根節點注入
store
):
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射為 `this.$store.dispatch('increment')`
// `mapActions` 也支援載荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射為 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射為 `this.$store.dispatch('increment')`
})
}
}