Vue路由
1.用name傳遞參數
在路由文件里配置name屬性
routes: [
{
path: '/',
name: 'Hello',
component: Hello
}
]
在.vue模板里用$router.name的形式接收:<p>{{ $route.name}}</p>
2.通過<router-link> 標簽中的to傳參
<router-link>標簽中的to屬性進行傳參,需要對to進行一個綁定,用:to。
格式:
<router-link :to="{name:xxx,params:{key:value}}">valueString</router-link>
用法:
<router-link :to="{name:'hi1',params:{username:'jspang'}}">Hi頁面1</router-link>
路由配置:
{path:'/hi1',name:'hi1',component:Hi1}
頁面接收:
{{$route.params.username}}
3.單頁面多路由區域操作
<router-view ></router-view>
<router-view name="left"></router-view>
<router-view name="right"></router-view>
路由配置:
export default new Router({
routes: [
{path: '/', components: { default:Hello, left:Hi1, right:Hi2 }},
{path: '/Hi', components: {default:Hello, left:Hi2, right:Hi1 }}
]
})
4.vue-router利用url傳遞參數
:冒號的形式傳遞參數
配置路由:
{ path:'/params/:newsId/:newsTitle' , component:Params }
.vue組件中:
用法:<router-link to="/params/198/jspang website is very good">params</router-link>
取值:
<p>新聞ID:{{ $route.params.newsId}}</p>
<p>新聞標題:{{ $route.params.newsTitle}}</p>
正則表達式在URL傳值用法:
要求傳遞參數ID只能是數字的形式,傳值時有個基本類型判斷
用法:path:'/params/:newsId(\\d+)/:newsTitle',
5.redirect基本重定向
{ path:'/goback' , redirect:'/' }
重定向時傳遞參數
{ path:'/goParams/:newsId(\\d+)/:newsTitle' , redirect:'/params/:newsId(\\d+)/:newsTitle' }
6.alias別名的使用
路由配置: { path: '/hi1', component: Hi1, alias:'/jspang' }
用法:<router-link to="/jspang">jspang</router-link>
注意:
別名請不要用在path為’/’中,如下代碼的別名是不起作用的。
{ path: '/', component: Hello, alias:'/home'}
7.路由中的鈎子
(1)路由配置文件中的鈎子函數,只能寫一個beforeEnter
{
path:'/params/:newsId(\\d+)/:newsTitle',
component:Params,
beforeEnter:(to,from,next)=>{
console.log('我進入了params模板');
console.log(to);
console.log(from);
next();
},
三個參數:
- to:路由將要跳轉的路徑信息,信息是包含在對像里邊的。
- from:路徑跳轉前的路徑信息,也是一個對象的形式。
- next:路由的控制參數,常用的有next(true)和next(false)。
(2)在模板中的鈎子函數
beforeRouteEnter:在路由進入前的鈎子函數。
beforeRouteLeave:在路由離開前的鈎子函數。