理解: 一個路由(route)就是一組映射關(guān)系(key - value),多個路由需要路由器(router)進(jìn)行管理肥橙。
前端路由:key是路徑魄宏,value是組件。
1.基本使用
安裝vue-router存筏,命令:npm i vue-router
應(yīng)用插件:Vue.use(VueRouter)
編寫router配置項:
//引入VueRouter
importVueRouterfrom'vue-router'
//引入Luyou 組件
importAboutfrom'../components/About'
importHomefrom'../components/Home'
//創(chuàng)建router實(shí)例對象宠互,去管理一組一組的路由規(guī)則
constrouter=newVueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
//暴露router
exportdefaultrouter
實(shí)現(xiàn)切換(active-class可配置高亮樣式)
<router-linkactive-class="active"to="/about">About</router-link>
指定展示位置
<router-view></router-view>
2.幾個注意點(diǎn)
路由組件通常存放在pages文件夾,一般組件通常存放在components文件夾椭坚。
通過切換予跌,“隱藏”了的路由組件,默認(rèn)是被銷毀掉的善茎,需要的時候再去掛載券册。
每個組件都有自己的$route屬性,里面存儲著自己的路由信息。
整個應(yīng)用只有一個router烁焙,可以通過組件的$router屬性獲取到航邢。
3.多級路由(多級路由)
配置路由規(guī)則,使用children配置項:
routes:[
{
path:'/about',
component:About,
},
{
path:'/home',
component:Home,
children:[//通過children配置子級路由
{
path:'news',//此處一定不要寫:/news
component:News
},
{
path:'message',//此處一定不要寫:/message
component:Message
}
]
}
]
跳轉(zhuǎn)(要寫完整路徑):
<router-linkto="/home/news">News</router-link>
4.路由的query參數(shù)
傳遞參數(shù)
<router-link:to="/home/message/detail?id=666&title=你好">跳轉(zhuǎn)</router-link>
<router-link
:to="{
path:'/home/message/detail',
query:{
id:666,
title:'你好'
}
}"
跳轉(zhuǎn)</router-link>
接收參數(shù):
$route.query.id
$route.query.title
5.命名路由
作用:可以簡化路由的跳轉(zhuǎn)骄蝇。
如何使用
給路由命名:
{
path:'/demo',
component:Demo,
children:[
{
path:'test',
component:Test,
children:[
{
name:'hello'//給路由命名
path:'welcome',
component:Hello,
}
]
}
]
}
簡化跳轉(zhuǎn):
<router-linkto="/demo/test/welcome">跳轉(zhuǎn)</router-link>
<router-link:to="{name:'hello'}">跳轉(zhuǎn)</router-link>
<router-link
:to="{
name:'hello',
query:{
id:666,
title:'你好'
}
}"
跳轉(zhuǎn)</router-link>
6.路由的params參數(shù)
配置路由膳殷,聲明接收params參數(shù)
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title',//使用占位符聲明接收params參數(shù)
component:Detail
}
]
}
]
}
傳遞參數(shù)
<router-link:to="/home/message/detail/666/你好">跳轉(zhuǎn)</router-link>
<router-link
:to="{
name:'xiangqing',
params:{
id:666,
title:'你好'
}
}"
跳轉(zhuǎn)</router-link>
特別注意:路由攜帶params參數(shù)時,若使用to的對象寫法九火,則不能使用path配置項赚窃,必須使用name配置!
接收參數(shù):
$route.params.id
$route.params.title