【问题标题】:Vuex dispatch action data is undefinedVuex 调度动作数据未定义
【发布时间】:2020-12-28 02:08:26
【问题描述】:

vuex 有问题。

我的商店是这样的:

state: {
    ...
    client: {
        name: '',
    },
},
mutations: {
    ...
    SET_CLIENT: (state, client) => {
    state.client = Object.assign({}, client);
    },
},
actions: {
    ...
    set_client({ commit }, { client }) {
        commit('SET_CLIENT', client);
    },
},
getters: {
    ...
    client: state => state.client,
},

在我的 vue 路由器中,如果我的参数中有“client_id”,我会检查每条路由。如果为真,我将使用 axios 向服务器发送请求以获取客户端数据:

router.beforeEach((to, from, next) => {
    if ('client_id' in to.params) {
        const id = to.params.client_id;

        axios.get('client/' + id).then((response) => {
            const data = response.data;
            store.dispatch("set_client", data);
        })
        .catch((error) => {
            console.log(error);
        });
    }
    
    next();
})

在使用 next() 语句加载的组件中,我在模板中打印 client.name。例如:

<template>
    <div>
        ...
        <v-card-title>{{ $store.getters.client.name }}</v-card-title>
        ...
    </div>
</template>

但卡片标题仍然为空。

为什么?

对于其他数据,例如一组客户端,效果很好..

【问题讨论】:

  • 我之前也遇到过同样的问题,试试用 state.client = JSON.parse(JSON.stringify(client)) 代替 Object.assign 看看是否有效
  • 为什么不使用像 state.client = client payload 这样的简单赋值?

标签: vue.js vuejs2 vuex vue-router


【解决方案1】:

尝试在突变中使用 Vue.set()。您将一个新对象分配给商店。这不会是被动的,因此您看不到新值。 https://vuejs.org/v2/guide/reactivity.html

mutations: {
    ...
    SET_CLIENT: (state, client) => {
    Vue.set(state.client, {...client})
    },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2020-03-10
    • 2020-11-03
    • 2021-11-10
    • 1970-01-01
    • 2019-12-09
    • 2019-05-13
    • 2020-05-22
    相关资源
    最近更新 更多