programing

각각 전에 VueRouter에서 약속된 getter 사용

firstcheck 2022. 7. 28. 22:12
반응형

각각 전에 VueRouter에서 약속된 getter 사용

이 기능을 사용하는 데 어려움을 겪고 있습니다.vuex.getters로부터 계산됩니다.vuex.actions로서if에 있어서의 성명.router.beforeEach.

제가 하려는 일은 다음과 같습니다.

  1. 사용자가 사이트에 들어갈 때마다 개체 어레이를 가져옵니다.

  2. 그리고 나서array.find()같은 총알로 하나의 물체를 겨냥하다router.params.id사용자가 직접 URL을 사용하여 사이트에 들어간 경우.

  3. 루트를 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

반응형