理解:一个路由(route)就是一组映射关系(key-value),多个路由需要路由器(router)进行管理。每个组件都有自己得$route
属性,里面存储着自己的路由信息。整个应用只有一个router,可以通过组件的$router
属性获取。
基本使用
1.安装vue-router,命令:npm i vue-router
2.应用插件:Vue.use(VueRouter)
3.编写router配置项:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
4.实现切换(active-class可配置高亮样式)
<router-link active-class="active" to="/about">About</router-link>
5.指定展示位置
<router-view></router-view>
多级路由
1.配置路由规则时,使用children配置项
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
children:[
{
path:'person',
name:'Person',
component: () => import('../views/Person'),
children:[
{
name:'Info',
path:'info',
component: () => import('../views/Info')
}
]
}
]
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
2.跳转(要写完整路径):
<router-link to="/about/news">News</router-link>
路由的query参数
1.传递参数
<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
<!-- 跳转并携带query参数,to的对象写法 -->
<router-link
:to="{
path:'/home/message/detail',
query:{
id:666,
title:'你好'
}
}"
>跳转</router-link>
2.接收参数:
$route.query.id
$route.query.title
命名路由
1.作用:简化路由的跳转
2.使用:
1. 命名
const routes = [
{
path: '/',
name: 'Home', //路由命名
component: Home
}
]
2.跳转
<router-link :to="{
name:'Info', //跳转到name=Info的组件
query:{
name:person.name,
age:person.age
}
}">
成员{{index}}
</router-link>
路由的params参数
1.配置路由,声明接收params参数
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
children:[
{
path:'person',
name:'Person',
component: () => import('../views/Person'),
children:[
{
name:'Info',
path:'info/:name/:age', //使用占位符声明接收params参数
component: () => import('../views/Info')
}
]
}
]
}
2.传递参数
<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="/about/info/张三/18">跳转</router-link>
<!-- 跳转并携带params参数,to的对象写法 -->
<router-link :to="{
name:'Info', //跳转到name=Info的组件
params:{ //params参数
name:person.name,
age:person.age
}
}">
成员{{index}}
</router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
3.接收参数
<div>
<p>姓名:{{$route.params.name}}</p>
<p>年龄:{{$route.params.age}}</p>
</div>