携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情 >>
什么是重定向
重定向:就是通过各种方法将各种网络请求重新定个方向转到其它位置。 路由重定向:当你输入了网址a时,自动跳转到网址b并展示b网址下的页面。
Eg:当输入https://www.hao123.com
时会自动跳转到https://www.hao123.com/?from=offline_host
重定向的作用
- 一般用在不同页面跳转到同一页面或者是跳转到同一组件
- 一般来说网页根目录为
/
,后面没有当前页面的信息,不利于用户体验
重定向的用法
- 重定向到同级路由
- 导航守卫不会应用在跳转路由上,而是应用在目标路由上,如下:在
/
上面添加路由守卫是没有作用的,应该添加在/index
上面
- 导航守卫不会应用在跳转路由上,而是应用在目标路由上,如下:在
//'/'重定向到同级的'/index'
const routes = [
//重定向
{
path:'/',
name:'home',
compoent:home,
redirect:'/index'
}
//目标路由
{
path:'/index',
name:'Home',
component:index
}
]
- 重定向到子路由
//'/'重定向到子路由的'/index'
const routers = [
//重定向
{
path:'/',
name:'fatherPage',
compoent:fatherPage,
redirect:'/index',
//目标路由
children:[{
path:'/index',
name:'index',
conpoent:index
}]
}
]
-
带参数重定向
1、query(会暴露参数)
const routers = [
//重定向
{
path:'/',
name:'home',
conpoent:home,
redirect:'/targetPage'
}
//目标路由
{
path:'/targetPage',
name:'targetPage',
conpoent:targetPage
}
]
//发起跳转(三种方式都可以)
this.$router.push({name:'home',query:{val:'值'}})
this.$router.push({path:'/home',query:{id:'值'}})
this.$router.push('/home?id=值')
2、params(会隐藏参数)
const routers = [
//重定向
{
path:'/',
name:'home',
conpoent:home,
redirect:{name:'targetPage'}
}
//目标路由
{
path:'/targetPage',
name:'targetPage',
conpoent:targetPage
}
]
//发起跳转
this.$router.push({name:'home',params:{id:'值'}})
重定向和别名
-
重定向:进入a页面 --> 重定向到b页面
- 两个路由都是真实存在的,只是经过了一次跳转
-
别名:进入a页面 --> 把a页面的路由变成b页面的路由
- 路由展示访问的是b页面,但是实际上访问的还是a