专栏目录请点击
简介
vuex4为我们暴露出的组合式api只有一个,那就是
useStore
,他和this.$store
是等价的
访问相关属性
访问state和getter
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// 在 computed 函数中访问 state
count: computed(() => store.state.count),
// 在 computed 函数中访问 getter
double: computed(() => store.getters.double)
}
}
}
访问mutation 和 action
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// 使用 mutation
increment: () => store.commit('increment'),
// 使用 action
asyncIncrement: () => store.dispatch('asyncIncrement')
}
}
}
注意
在我们使用组合式api的时候,也可以使用ES6的接口语法
const {commit} = useStore()