天天看点

vue-router 重定向到动态的 path 中Vue Router 重定向到动态的 path 中

Vue Router 重定向到动态的 path 中

背景

在 vue-router 中,重定向到某个页面采用下面的配置

const routes = [
  {
    path: '/test',
    redirect: '/aaa',
  },
]
           

但是如果 redirect 中的路径需要动态生成,由于定义的时候是同步代码,无法直接给 redirect 赋值。

async function reqRedirectUrl() {
  return '/aaa'
}

const routes = [
  {
    path: '/test',
    redirect: '***',
  },
]
           

解决方案

在定义路由是,使用 beforeEnter 进行拦截,该函数可以定义为 async 函数,

里面就可以获取到了动态的路径,再把路径传入到 next 中,实现了动态的重定向

async function reqRedirectUrl() {
  return '/aaa'
}

const routes = [
  {
    path: '/test',
    // vue 3 需要加上重定向字段,值随便写
    // redirect: '',
    async beforeEnter (to, from, next) {
      next(await reqRedirectUrl())
    }
  },
]
           

注意

如果有什么更好的方案,欢迎评论一起学习,目前找到的解决办法就是这样

继续阅读