【问题标题】:dynamic vue router - beforeEnter - infinite loop when using next()动态 vue 路由器 - beforeEnter - 使用 next() 时的无限循环
【发布时间】:2018-10-27 20:16:05
【问题描述】:

我正在尝试创建一个 SPA,显示奥地利每个州的经销商。例如,如果用户访问example.com/vienna,它会显示维也纳的每个经销商。但是如果用户访问example.com/paris,他仍然会被定向到动态路由 /paris 但当然不会显示任何内容。

所以我的方法是检查用户想要搜索的状态是否在状态列表中可用,因此将其定向到可用状态或将他重定向到 404 页面。

如果状态可用,它可以工作,但如果我尝试进入不存在的状态,我会陷入来自 next('/404') 的循环中

export default new Router({
  routes: [{
      path: '/',
      name: 'Home',
      component: Home
    },{
      path: '/:region',
      component: RegionQuery,
      beforeEnter: (to, from, next) => {

        let isRegion = false;
        let allRegions = storeConfig.state.states;
        let toRegion = to.params.region;

        for(var i in allRegions){
          if(allRegions[i].route === toRegion){
            isRegion = true;
          }
        }

        if (isRegion) {
          next();
        } else {
          next('/404');
        }
      }
    },
    {
      path: '/404',
      name: '404',
      component: NotFound
    },
    {
      path: '*',
      redirect: '/404'
    },
  ],
})

我做错了什么还是有更好的方法来解决我的问题?

【问题讨论】:

    标签: javascript vue.js routing vue-router


    【解决方案1】:

    /404 匹配到/:region

    你需要改变你的路径顺序

    export default new Router({
      routes: [{
          path: '/',
          name: 'Home',
          component: Home
        },
        {
          path: '/404',
          name: '404',
          component: NotFound
        },{
          path: '/:region',
          component: RegionQuery,
          beforeEnter: (to, from, next) => {
    
            let isRegion = false;
            let allRegions = storeConfig.state.states;
            let toRegion = to.params.region;
    
            for(var i in allRegions){
              if(allRegions[i].route === toRegion){
                isRegion = true;
              }
            }
    
            if (isRegion) {
              next();
            } else {
              next('/404');
            }
          }
        },
        {
          path: '*',
          redirect: '/404'
        },
      ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多