반응형
각각 전에 VueRouter에서 약속된 getter 사용
이 기능을 사용하는 데 어려움을 겪고 있습니다.vuex.getters
로부터 계산됩니다.vuex.actions
로서if
에 있어서의 성명.router.beforeEach
.
제가 하려는 일은 다음과 같습니다.
사용자가 사이트에 들어갈 때마다 개체 어레이를 가져옵니다.
그리고 나서
array.find()
같은 총알로 하나의 물체를 겨냥하다router.params.id
사용자가 직접 URL을 사용하여 사이트에 들어간 경우.루트를 404로 리다이렉트 합니다.
router.params.id
오브젝트 배열 내의 어떤 슬래그와도 일치하지 않습니다.
나의 접근법은 다음과 같다.
const router = new VueRouter(
{
routes: [
{
path: '/list/:id',
name: 'list'
},
{
path: '/edit/:id',
name: 'edit'
},
//other routes
{
path: '/*',
name: '404'
}
]
}
);
router.beforeEach((to, from, next)=>{
if ( !store.state.lists.length ){
// fetch Object Array when user first enter
store.dispatch('fetchLists');
}
if ( to.name === 'list' || to.name === 'edit'){
// limit route only 'list' & 'edit', preventing passing undefined params
store.commit('cloneParams', to);
// determine if currentMonth has a valid slug, if not go to 404
store.getters.currentMonth.slug !== '' ? next() : next('/404');
} else {
next();
}
});
getters: {
currentMonth(state){
var template = {
month: '',
slug: '',
data: []
}
var obj = template;
if ( state.lists.length ) {
obj = state.lists.find(current => current.slug === state.paramsID);
if ( obj === undefined ){
obj = template
}
}
return obj;
},
actions: {
fetchLists({commit}){
axios('/lists').then(
res=>{
commit('storeList', res);
}
)
},
mutations: {
storeList(state, res){
state.lists = res.data;
},
cloneParams(state, to){
state.paramsID = to.params.id;
},
하지만, 나는 그 겟터가currentMonth
개체 배열 후 업데이트되지 않음store.state.lists
취득되어 404로 이동합니다.그러는 동안, 그것은 완벽하게 잘 작동합니다.store.state.lists
사용자가 이 SPA의 다른 페이지로 이동하면 Import되어 저장됩니다.
루트 가드는 api 결과를 확인하기 전에 http 요구가 완료될 때까지 기다리지 않습니다.약속을 반환하다fetchLists
:
actions: {
fetchLists({commit}){
return axios('/lists').then(res => { // return the promise
commit('storeList', res);
})
},
그리고 항법 경비대에서 그 약속을 기다려라.
router.beforeEach(async (to, from, next) => { // async keyword
if ( !store.state.lists.length ){
await store.dispatch('fetchLists'); // Waiting for the promise
}
if ( to.name === 'list' || to.name === 'edit'){
// limit route only 'list' & 'edit', preventing passing undefined params
store.commit('cloneParams', to);
// determine if currentMonth has a valid slug, if not go to 404
store.getters.currentMonth.slug !== '' ? next() : next('/404');
} else {
next();
}
});
언급URL : https://stackoverflow.com/questions/65927674/use-promised-getter-in-vuerouter-beforeeach
반응형
'programing' 카테고리의 다른 글
{...}을(를) 하다} while (0) — 어떤 용도로 사용할 수 있습니까? (0) | 2022.07.28 |
---|---|
Jest Vuex: 생성된 후크 오류: "TypeError: 정의되지 않은 속성 '디스패치'를 읽을 수 없습니다." (0) | 2022.07.28 |
Vue 및 TypeScript 클래스 데코레이터 구문과 함께 외부에서 정의된 구성 요소 사용 (0) | 2022.07.28 |
JDBC 결과 세트와 문은 나중에 닫히지만 별도로 닫아야 합니까? (0) | 2022.07.27 |
Vuex 이거.$store는 함수가 아니라 이것입니다.$store.syslog가 실행됩니다. (0) | 2022.07.27 |