小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
在Vue3中我们使用状态管理是和Vue2有些差异的,我们需要先获取store实例,在使用对应的方法。
状态管理在Vue3中的使用
我们可以通过调用 useStore 函数,来在 setup 钩子函数中访问 store。这与在组件中使用选项式 API 访问 this.$store 是等效的,如下:
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
我们需要注意的是:必须在setup中使用useStore后,才能使用store实例对应的方法。
使用 State 和 Getter
为了访问 state 和 getter,需要创建 computed 引用以保留响应性,这与在选项式 API 中创建计算属性等效,如下:
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)
}
}
}
我们需要注意的是:使用computed方法,让我们的数据保存响应性。
使用 Mutation 和 Action
要使用 mutation 和 action 时,只需要在 setup 钩子函数中调用 commit 和 dispatch 函数。
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// 使用 mutation
increment: () => store.commit('increment'),
// 使用 action
asyncIncrement: () => store.dispatch('asyncIncrement')
}
}
}
总结
我们第一步操作就是要通过useStore方法获取到 store 实例,然后在使用状态或者调用对应的函数,但是我们要记得:useStore只用在setup函数中。
想了解更多文章,传送门已开启:回首Vue3目录篇 !