路由:
1.理解:一个路由(route)就是一组映射关系(key-value),多个路由需要路由器(router进行管理)。
2.前端路由:key是路径,value是组件。
基本使用
1.安装vue-router,命令:npm i vue-router@3(vue2中使用)
2.应用插件:在main.js中引入并应用
import VueRouter from 'vue-router'
Vue.use(VueRouter)
编写router配置项
//引入VueRouter
import VueRout from 'vue-router'
//引入组件
import About from 'xxx'
import Home from 'xxx'
//创建router实例对象,去管理一组一组的路由规则
const router=new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
export default router
或
const router=new VueRouter({
routes:[
{
path:'/about',
component:()=>imoort ('@/views/xxx')
},
{
path:'/home',
component:()=>imoort ('@/views/xxx')
}
]
})
export default router
切换(ative-class可配置高亮样式)
<router-link active-class="active" to="/about">about</router-link/>
指定展示位置
<router-view></router-link>
注意:
1.路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹
2.通过切换,”隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载
3.每个组件都有自己的$route属性,里面存储着自己的路由信息
4.整个应用只有一个router,可以通过组建的$router属性获取到
多级路由(嵌套路由)
import Messag from 'xxx'
import News from 'xxx'
const router=new VueRouter({
routes:[
{
path:'/home',
component:Home,
children:[
{
path:'news',//子路由的path中无需/
component:News
},
{
path:'message',
component:Message
}
]
}
]
})
export default router
<router-link active-class="active" to="/home/news">news</router-link/>//跳转时路径为完整路径(需带着父组件的路径)
路由的query参数
1.传递参数
<router-link :to="`/home/message/detail?id=${item.id}&title=${item.title}`"跳转</router-link>
<router-link :to="{
path:'/home/message/detail',
query:{
id:item.id,
title:item.title
}
}"跳转</router-link>
2.接收参数
this.$route.query.id
this.$route.query.title
命名路由
1.作用:简化路由的跳转
2.使用
1.给路由命名
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
children:[
{
name:'xiangqing',
path:'detail',
component:Detail
}
]
]
}
]
2.简化跳转
//简化前
<router-link to="/home/news/detail">跳转</router-link>
//简化后
<router-link :to="{name:'xiangqing',query:{id:item.id,title,item.title}}">跳转</router-link>
路由的params参数
1.配置路由,声明接受params参数
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News,
children:{
name:'xiangqing',
path:'detail/:id/:title',//使用占位符声明接受params参数
component:Detail
}
}
]
}
2.传递参数
//跳转并携带params参数,to的字符串写法
<router-link :to="/home/message/detail/001/你好">跳转</router-link>
//跳转并携带params参数,to的对象写法
<router-link
:to="{
name:'xiangqing',
params:{
id:001,
title:'你好'
}
}"
//使用对象写法时,不能使用path配置项,必须使用name配置
3.接收参数
this.$route.params.id
this.$route.params.title
使用props接收路由参数
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News,
children:{
name:'xiangqing',
path:'detail/:id/:title',//使用占位符声明接受params参数
component:Detail,
props:{a:1,b:'hello'}//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件,不过数值是死的,固定为a:1,b:'hello'
props:true,//props的第二种写法,值为布尔值,若其为真,则会把该路由组件接收到的所有params参数,以props的形式传给Detail组件
props($route){
return {id:$route.query.id,title:$route.query.title}//props的第三种写法,值为函数
}或解构赋值为
props({$route}){
return {id:query.id,title:query.title}//props的第三种写法,值为函数
}
}
}
]
}
接收:
props:['a','b']
props:['id','title']
props:['id','title']