首页 > 解决方案 > 如何访问 Vuex 动态状态属性?

问题描述

如何使动态属性添加到 Vuex 状态响应?当调用任何未预定义的状态属性时,getter操作undefined的结果都会在刷新时返回。

Vuex 商店

interface State {
    ...
    profile: { [key: string]: any }
}

export default createStore<State>({
    state: {
        ...
        profile: {},
    },
    getters: {
        name: state => state.profile.name
    },
    mutations: {
        mSetUserProfile: ( state, payload ) => {
            Object.assign(state.profile, payload),
        }
    },
    actions: {
        aSetUserProfile: ({ commit }) => {
            db.collection(foo)
                .doc(bar)
                .get()
                .then(response => commit('mSetUserProfile', response))
        },
        aGetName: ({state}) => state.profile.name
    }
})

应用程序.vue

setup(){
    ...
    store.dispatch('aSetUserProfile')

    store.dispatch('aGetName') // returns 'undefined'
    store.getters.name         // returns 'undefined'
    ...
}

标签: javascripttypescriptvue.jsvuexvuejs3

解决方案


aGetName应该是吸气剂而不是动作。

aSetUserProfile包含一个错误,它不允许内部承诺被链接,它应该是:

    aSetUserProfile: ({ commit }) => {
        return db.collection(foo) ...

动作是异步的,它们的结果不应该立即可用。他们可以通过使用等待组件初始化<suspense>

async setup() {
  await store.dispatch('aSetUserProfile')
  ...

或者这可以在onMounted.


推荐阅读