返回
利用自定义 Hook 实现 setup 函数中便捷的使用 vuex 的 mapState
前端
2023-12-03 11:13:44
本文将通过介绍自定义 Hook 的方法,详细说明如何在 Vue 3 的 setup 函数中轻松使用 Vuex 的 mapState。
传统的 Vue 2 中使用 mapState
在传统的 Vue 2 中,我们使用 optionsAPI,使用 mapState 非常方便。我们可以直接在组件中使用:
export default {
computed: {
...mapState(['count'])
}
}
然后就可以直接使用 this.count 来获取 Vuex 中的 state 了。
Vue 3 中使用 mapState
但是在 Vue 3 中,我们使用 setup 函数,mapState 的使用变得比较繁琐。我们需要先使用 useStore() 来获取 store 实例,然后使用 store.state.count 来获取 Vuex 中的 state。
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
return {
count: store.state.count
}
}
}
封装自定义 Hook
为了简化在 Vue 3 的 setup 函数中使用 mapState,我们可以封装一个自定义 Hook。
import { useStore } from 'vuex'
export function useMapState(mapper) {
const store = useStore()
const state = {}
Object.keys(mapper).forEach((key) => {
const fn = mapper[key]
state[key] = computed(() => fn(store.state))
})
return state
}
然后就可以在 setup 函数中使用:
import { useMapState } from '@/hooks/useMapState'
export default {
setup() {
const state = useMapState({
count: state => state.count
})
return {
...state
}
}
}
这样就可以直接使用 this.count 来获取 Vuex 中的 state 了。
结语
通过使用自定义 Hook,我们可以简化在 Vue 3 的 setup 函数中使用 mapState,使代码更加简洁和易于维护。
感谢阅读!