请教一下 vue-router 中 addRoute 的问题

2022-01-12 09:53:26 +08:00
 qq309187341

如题,使用 addRoute 来动态添加路由的时候,从 store 里面调用 actions 的中一个方法从后端获取路由地址。然后再添加到路由中。 代码如下:

router.beforeEach(async (to, from, next) => {
  NProgress.start(); // NProgress 开始 
  if (allowList.includes(to.name)) {
    // 若跳转页面非免登录名单,则直接进入
    next();
  } else {
    // 若当前页面需要登录
    // 则判断当前页面是否已经拥有登录权限 token
    if (storage.get('token')) {
      const mainStore = useMainStore();
      if (mainStore.routerList === null) {
        mainStore.getRouterList().then(res => {
          console.log(res)
          router.addRoute(res)
          next()
        })
      } else {
        next()
      }
    } else {
      // 没有 token 内容,所以进入登录页面
      next({ path: '/user' })
    }
  }
})

但是浏览器运行到时候却报了警告!

vue-router.esm-bundler.js:72 [Vue Router warn]: The "next" callback was never called inside of :
async (to, from, next) => {
  NProgress.start(); // NProgress 开始 
  if (allowList.includes(to.name)) {
    // 若跳转页面非免登录名单,则直接进入
    next();
  } else {
    // 若当前页面需要登录
    // 则判断当前页面是否已经拥有登录权限 token
    if (storage.get('token')) {
      const mainStore = useMainStore();
      if (mainStore.routerList === null) {
        mainStore.getRouterList().then(res => {
          console.log(res)
          router.addRoute(res)
          next()
        })
      } else {
        next()
      }
    } else {
      // 没有 token 内容,所以进入登录页面
      next({ path: '/user' })
    }
  }
}
. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.

难道 next 方法不能放在函数中????

2496 次点击
所在节点    Vue.js
8 条回复
yamedie
2022-01-12 09:58:48 +08:00
改成这种写法试一下吧
const res = await mainStore.getRouterList();
// res.xxxxx 略
next();

然后动态加载路由也不适合放在路由守卫里吧, 我觉得应该放在 App.vue 的 created 或 main.js 之类的位置
qq309187341
2022-01-12 10:05:21 +08:00
@yamedie 忘记你这种方式好像也是可以的。。。
我看几个大的脚手架好像都是放在路由守卫里面进行添加的。。。
tutou
2022-01-12 10:05:38 +08:00
首先 async await 要一起用。第二实现你的需求,不用动态添加路由,你都 beforeEach 判断了,没有 token 强制跳登录页面就行了,而且还可以做到登录后再跳回来
qq309187341
2022-01-12 10:24:18 +08:00
@tutou async 是之前写了,忘记删除了。一楼说起来,我才想起来可以使用这种方式解决 next()控制台报错的问题。至于动态路由的问题,只是因为需要根据后端来对不同角色生成不同菜单。
wu67
2022-01-12 10:47:47 +08:00
其实我觉得, 不对路由做改动更好. 在守卫里面判断权限 /token, 然后做重定向即可. 这样可以避免在地址栏输入无权限的 url 时 404.
walpurgis
2022-01-12 13:26:03 +08:00
同建议不要动态路由,开发和 debug 都麻烦
后端只下发权限,前端根据权限把路由配置过滤一遍生成菜单列表,分离模式下后端不应该知道前端路由
jqtmviyu
2022-01-12 14:45:25 +08:00
估计是因为还要开放一个路由权限控制页面给用户设置, 路由是存在数据库里的, 导航菜单由后端返回生成.
wunonglin
2022-01-12 14:46:05 +08:00
路走错了。你这功能这么设计本身就有问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/827734

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX