组合式 API
要在 setup 钩子中访问 store,可以调用 useStore 函数。这等同于使用选项 API 在组件中检索 this.$store。
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
访问状态和 Getter
为了访问状态和 Getter,您需要创建 computed 引用以保留响应性。这等同于使用选项 API 创建计算属性。
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// access a state in computed function
count: computed(() => store.state.count),
// access a getter in computed function
double: computed(() => store.getters.double)
}
}
}
访问 Mutation 和 Action
访问 Mutation 和 Action 时,您只需在 setup 钩子中提供 commit 和 dispatch 方法。
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// access a mutation
increment: () => store.commit('increment'),
// access an action
asyncIncrement: () => store.dispatch('asyncIncrement')
}
}
}
示例
查看 组合式 API 示例,以查看利用 Vuex 和 Vue 的组合式 API 的示例应用程序。