当我在 Mounted() 生命周期挂钩中的 App.vue 组件中分派一个操作时,它会在其他组件加载后运行。我在操作中使用 async/await 并安装了生命周期挂钩。
应用程序.vue 文件
methods: {
...mapActions({
setUsers: "setUsers",
}),
},
async mounted() {
try {
await this.setUsers();
} catch (error) {
if (error) {
console.log(error);
}
}
},
Run Code Online (Sandbox Code Playgroud)
动作.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;
}
}
},
Run Code Online (Sandbox Code Playgroud)
在用户列表组件中,我需要从 vuex 获取用户。所以我使用 mapGetters 来获取用户列表。
...mapGetters({
getUsers: "getUsers",
}),
mounted() { …Run Code Online (Sandbox Code Playgroud)