【发布时间】:2021-04-14 19:03:20
【问题描述】:
当我在 Mounted() 生命周期钩子中调度 App.vue 组件中的操作时,它会在其他组件加载后运行。我在我的操作中使用 async/await 并挂载了生命周期钩子。
App.vue 文件
methods: {
...mapActions({
setUsers: "setUsers",
}),
},
async mounted() {
try {
await this.setUsers();
} catch (error) {
if (error) {
console.log(error);
}
}
},
action.js 文件:
async setUsers(context) {
try {
const response = await axios.get('/get-users');
console.log('setting users');
if (response.data.success) {
context.commit('setUsers', {
data: response.data.data,
});
}
} catch (error) {
if (error) {
throw error;
}
}
},
在用户列表组件中,我需要从 vuex 获取用户。所以我使用 mapGetters 来获取用户列表。
...mapGetters({
getUsers: "getUsers",
}),
mounted() {
console.log(this.getUsers);
},
但问题是在控制台记录this.getUsers 之后运行“设置用户”控制台登录。
在用户列表组件中,我可以在模板中使用 getUsers,但是当我尝试控制台日志 this.getUsers 时,它什么也没提供。
如何在运行任何其他组件之前运行app.vue 文件?
【问题讨论】:
标签: vue.js vuejs2 vue-component vuex