vuex 解決了元件以及路由之間互相通訊和實時更新的問題
1. State
state 提供統一公告資源,所有公共的變量可以放在 state 中存儲
// 聲明全局變量
const store = new Vuex.Store({
state: { count: 0 }
})
/**
* 調用全局變量
* 方法一: this.$store.state 調用
*/
this.$store.state.count // this 指向全局 vue 執行個體
/**
* 方法二: mapState API
*/
import { mapState } from 'vuex'
computed: {
...mapState(['count'])
}
2. Mutation
Mutation 用來修改 state 中的值,注意,不能直接修改 state 中的值,需要調用 Mutation
// 聲明全局變量 以及對應 Mutatiaon
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, data) {
// 可以通過 state 取到變量的值
// data 是傳遞的參數
state.count = data
}
},
})
// 觸發方法
this.$store.commit('count', 1)
// mapMutations API
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add']),
vuexAdd () {
// 直接調用并傳參即可
this.add(1)
}
}
2. Mutation
Mutation 用來修改 state 中的值,注意,不能直接修改 state 中的值,需要調用 Mutation
// 聲明全局變量 以及對應 Mutatiaon
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, data) {
// 可以通過 state 取到變量的值
// data 是傳遞的參數
state.count = data
}
},
})
// 觸發方法一
this.$store.commit('count', 1)
// 觸發方法二
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add']),
vuexAdd () {
// 直接調用并傳參即可
this.add(1)
}
}
注意: 此方法中不能有異步操作
3. Action
Action 用于解決 Mutation 中的異步操作
// 聲明全局變量 以及對應 Mutatiaon、Action
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, data) { state.count = data }
},
actions: {
addAsync (context, step) {
setTimeout(() => {
// 通過調用 mutations 中定義的方法,來實作異步修改 state
context.commit('add', step)
}, 1000)
}
}
})
// 觸發方法一
this.$store.dispatch('addAsync', 1)
// 觸發方法二
import { mapActions } from 'vuex'
methods: {
...mapActions(['addAsync']),
vuexAdd () {
// 直接調用并傳參即可
this.addAsync('add', 1)
}
}
4. Getter
Getter 可以講 state 中的變量,包裝成新的資料形式
// 聲明全局變量 以及對應 Getter
const store = new Vuex.Store({
state: { count: 0 },
Getter: {
showCount(state) {
return '目前的最新 count 是' + state.count
}
}
})
// 擷取方法一
this.$store.getters.showCount
// 擷取方法二
import { mapGetters } from 'vuex'
computed: {
...mapGetters (['showCount']),
}