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())
}
},
]
注意
如果有什麼更好的方案,歡迎評論一起學習,目前找到的解決辦法就是這樣