分派动作后获取 vuex 存储状态

S. *_*ooq 1 laravel vue.js vuex

我正在Laravel 6 + Vue + Vuex创建一个聊天应用程序。我想调用 vuex store 并在调度操作完成后获取状态,然后我想在 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
    });
}
Run Code Online (Sandbox Code Playgroud)

动作.js

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

mutators.js

setContacts: (state, users) => {
    state.contacts = users;
},
Run Code Online (Sandbox Code Playgroud)

请参阅下面的屏幕截图。调度的 then 方法在action.js中的setContacts之前运行。

console.logs 的图像

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

getters.js

getContacts: (state) => {
    return state.contacts;
}
Run Code Online (Sandbox Code Playgroud)

我还尝试在安装的then中调用计算属性,但它不起作用。另外,是否应该像 then 方法中那样在action.jssetContacts的 console.log 之后挂载运行中“调度调用” ?谢谢!

Din*_*mić 5

也许你可以将 axios 调用包装在另一个承诺中。

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)
     })

})
Run Code Online (Sandbox Code Playgroud)

进而

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

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