반응형
라우터에서 ASync/Awit가 예상대로 작동하지 않습니다.교도소에 있는 각 간수들 전에?
이것은 라우터 가드입니다.
router.beforeEach(async (to,from,next)=>{
await store.dispatch('GetPermission');
if(to.matched.some(record => record.meta.requireAuth)){
let permissions=store.state.permissions; //getting empty
console.log(permissions);
if(permissions.filter(per => (per.name === 'read_list').length!=0)){
next({
path:'/dashboard/create'
})
}
else{
next()
}
}
// else if(to.matched.some(record => record.meta.requireAuth)){
// if(store.token!=null){
// next({
// path:'/dashboard'
// })
// }
// else{
// next()
// }
// }
else{
next()
}
});
문제는 디스패치 방식에서 wait를 사용 중인데 처음에 비어 있는 권한의 상태 값을 얻을 수 없습니다. vuex 스토어 코드는 다음과 같습니다.
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:{}
}
내가 그것을 해결할 수 있도록 도와주시겠어요?
Vuex의 작업은 비동기적입니다.호출 기능(작업 개시자)이 작업이 완료되었음을 알 수 있는 유일한 방법은 약속을 반환하고 나중에 해결하는 것입니다.
다음은 예를 제시하겠습니다.myAction은 Promise를 반환하고 http 콜을 발신하여 나중에 Promise를 해결하거나 거부합니다.모두 비동기적으로 실행됩니다.
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
이제 Vue 구성 요소가 myAction을 시작하면 이 Promise 개체를 가져와 성공 여부를 확인할 수 있습니다.다음은 Vue 구성 요소의 샘플 코드입니다.
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
또, 허가가 일치하지 않는 경우는, 같은 루트를 호출합니다.이 경우, 항상 같은 루트를 호출해 무한 루프를 만듭니다.권한이 거부된 경우 액세스 거부 페이지로 리디렉션합니다.
언급URL : https://stackoverflow.com/questions/65056616/async-await-is-not-working-as-expected-in-router-beforeeach-guard-in-vue
반응형
'programing' 카테고리의 다른 글
Java 8의 map() 메서드와 platMap() 메서드의 차이점은 무엇입니까? (0) | 2022.08.10 |
---|---|
0x 표기법을 사용한 숫자는 무엇을 의미합니까? (0) | 2022.08.10 |
NULL, '\0'과 0의 차이점은 무엇입니까? (0) | 2022.08.10 |
(x ^ 0x1) != 0은 무슨 뜻입니까? (0) | 2022.08.10 |
Eclipse가 "Java was started but exit code = 1" 오류 메시지를 반환합니다. (0) | 2022.08.10 |