This is my routing guard:
router.beforeEach(async (to, from, next) => { await store.dispatch('GetPermission'); if (to.matched.some(record => record.meta.requireAuth)) { let permissions = store.state.permissions; //获取到的是空值 console.log(permissions); if (permissions.filter(per => (per.name === 'read_list').length != 0)) { next({ path: '/dashboard/create' }) } else { next() } } else { next() } });
The problem is that although I used await in the dispatch method, I did not get the status value of the initially empty permissions This is the code of vuex store:
GetPermission(context) { axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token axios.get('http://127.0.0.1:8000/api/user').then((response) => { console.log(response) context.commit('Permissions', response.data.permission) }) } //mutation: Permissions(state, payload) { state.permissions = payload } //state state: { error: '', token: localStorage.getItem('token') || null, permissions: '', success: '', isLoggedin: '', LoggedUser: {} }
Please help me solve this problem, thank you!
P粉3500367832023-11-07 18:13:06
In Vuex, operations are asynchronous. The only way to let the calling function (the initiator of the operation) know that the operation is complete is by returning a Promise and resolving it later.
Here's an example: myAction returns a Promise, makes an http call, and later asynchronously resolves or rejects the Promise.
actions: { myAction(context, data) { return new Promise((resolve, reject) => { // 在这里执行一些操作... 比如使用vue-resource进行http调用 this.$http("/api/something").then(response => { // http成功,调用mutator并在状态中更改一些内容 resolve(response); // 让调用函数知道http完成了。你可以发送一些数据回去 }, error => { // http失败,让调用函数知道操作没有成功 reject(error); }) }) }
}
Now, when your Vue component launches myAction, it will get this Promise object and can know whether it succeeded. Here is some sample code for Vue components:
export default { mounted: function() { // 这个组件刚刚创建。让我们在这里使用一个操作来获取一些数据 this.$store.dispatch("myAction").then(response => { console.log("获取到了一些数据,现在让我们在这个组件中显示一些东西") }, error => { console.error("从服务器获取不到任何数据。提示用户检查网络连接并重试") }) }
}
Additionally, when there is no permission match, you call the same route, which will keep calling the same route and cause an infinite loop. If permission is denied, redirect to the access denied page.