【问题标题】:Use promised getter in VueRouter beforeEach在 VueRouter beforeEach 中使用承诺的 getter
【发布时间】:2021-05-01 18:59:05
【问题描述】:

我一直在努力使用vuex.getters,它是从vuex.actions 计算出来的,作为router.beforeEach 中的if 语句。

这是我想要做的:

  1. 每次用户进入网站时获取一组对象。

  2. 然后使用array.find()根据router.params.id定位具有相同slug的一个对象,以防用户通过直接url进入站点。

  3. 如果 router.params.id 与对象数组中的任何 slug 都不匹配,则将路由重定向到 404。

这是我的方法

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;
  },

但是,我发现在获取对象数组 store.state.lists 并转到 404 后,getter currentMonth 不会更新。同时,当用户转到下一个其他对象时,在获取并存储 store.state.lists 后它工作得很好此 SPA 的页面。

【问题讨论】:

    标签: javascript vue.js vuex vue-router es6-promise


    【解决方案1】:

    在检查 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();
      }
    
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 2016-07-27
      • 2021-04-27
      • 2019-10-31
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多