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!
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.
}
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:
}
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.