重定向也是通过 routes 配置来完成,下面例子是从 /home 重定向到 /:
const routes = [{ path: '/home', redirect: '/' }]
重定向的目标也可以是一个命名的路由:
const routes = [{ path: '/home', redirect: { name: 'homepage' } }]
也可以是一个方法,动态返回重定向目标:
const routes = [ { // /search/screens -> /search?q=screens path: '/search/:searchtext', redirect: to => { // 方法接收目标路由作为参数 // return 重定向的字符串路径/路径对象 return { path: '/search', query: { q: to.params.searchtext } } }, }, { path: '/search', // ... },]
别名将 / 别名为 /home,意味着当用户访问 /home 时,url 仍然是 /home,但会被匹配为用户正在访问 /。
const routes = [{ path: '/', component: homepage, alias: '/home' }]
通过别名,可以自由地将 ui 结构映射到一个任意的 url,而不受配置的嵌套结构的限制。使别名以 / 开头,以使嵌套路径中的路径成为绝对路径。甚至可以将两者结合起来,用一个数组提供多个别名:
const routes = [ { path: '/users', component: userslayout, children: [ // 为这 3 个 url 呈现 userlist // - /users // - /users/list // - /people { path: '', component: userlist, alias: ['/people', 'list'] }, ], },]
/people 是绝对路径的写法,即可以直接通过 /people 来访问。
list 是相对路径的写法,即url会拼接父级的路径 → /users/list。
注意:如果路由有参数,请确保在任何绝对别名中包含它们:
const routes = [ { path: '/users/:id', component: usersbyidlayout, children: [ // 为这 3 个 url 呈现 userdetails // - /users/24 // - /users/24/profile // - /24 { path: 'profile', component: userdetails, alias: ['/:id', ''] }, ], },]
【相关推荐:vue.js视频教程】
以上就是举例说明vue router路由重定向与别名设置的详细内容。
