【问题标题】:Get vuex store state after dispatching an action调度操作后获取 vuex 存储状态
【发布时间】:2020-06-27 10:53:26
【问题描述】:

我正在 Laravel 6 + Vue + Vuex 中创建一个聊天应用程序。我想在调度操作完成后调用 vuex 存储并获取一个状态,然后我想在我的 vue 组件中对该状态进行一些处理。

ChatWindow组件中

mounted: function () {
    this.$store.dispatch('setContacts').then(() => {
        console.log('dispatch called')
        // I want to call the getter here and set one of the data property
    });
}

action.js

setContacts: (context) => {
    axios.post('/users').then(response => {
        let users = response.data;
        // consoled for testing
        console.log(users);
        context.commit('setContacts', users);
    });
}

mutators.js

setContacts: (state, users) => {
    state.contacts = users;
},

请看下面的截图。 dispatchthen 方法在 action.js 中的 setContacts 之前运行。

我需要在完成 dispatch 操作后调用 getter。 (这将有效地设置联系人状态)。然后,我想像这样通过 getContacts getter 获取联系人。

getters.js

getContacts: (state) => {
    return state.contacts;
}

我还尝试在 mounted 中调用 then 中的计算属性,但没有成功。另外,在 action.js 中的 setContacts 的 console.log 之后的挂载运行中是否应该“调度调用”,因为它在 then 方法中?谢谢!

【问题讨论】:

    标签: laravel vue.js vuex


    【解决方案1】:

    也许您可以将 axios 调用包装在另一个 Promise 中。

    return new Promise((resolve, reject) => {
    
       axios.post('/users')
         .then(response => {
            let users = response.data;
            // consoled for testing
            console.log(users);
            context.commit('setContacts', users);
            resolve('Success')
         })
         .catch(error => {
            reject(error)
         })
    
    })
    

    然后

    this.$store.dispatch('setContacts')
       .then(() => {
           console.log('dispatch called')
           console.log('getter ', this.$store.getters.contacts)
       });
    

    让我知道会发生什么。它适用于我尝试的一个小型演示。

    【讨论】:

    • @S.Farooq 很棒的伙伴
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2018-05-02
    • 2020-04-30
    相关资源
    最近更新 更多