# 路由

# 基本路由

  1. 安装vue-router,命令npm i vue-router(22.2以后默认vue-router是4版本->vue3+)
  2. 应用插件Vue.use(VueRouter)
  3. router配置项 src/router/index.js
import VueRouter from 'vue-router'			// 引入VueRouter
import About from '../components/About'	// 路由组件
import Home from '../components/Home'		// 路由组件

// 创建router实例对象,去管理一组一组的路由规则
const router = new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home
		}
	]
})

//暴露router
export default router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  1. 实现切换 <router-link></router-link>浏览器会被替换为a标签 active-class可配置高亮样式
<router-link active-class="active" to="/about">About</router-link>
1
  1. 指定展示位<router-view></router-view>
  • 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载
  • 每个组件都有自己的$route属性,里面存储着自己的路由信息
  • 整个应用只有一个router,可以通过组件的$router属性获取到

# 多级路由

routes:[
	{
		path:'/about',
		component:About,
	},
	{
		path:'/home',
		component:Home,
		children:[ 					// 通过children配置子级路由
			{
				path:'news', 		// 此处一定不要带斜杠,写成 /news
				component:News
			},
			{
				path:'message',	// 此处一定不要写成 /message
				component:Message
			}
		]
	}
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • 跳转要写完整路径 <router-link to="/home/news">News</router-link>

# 路由的 query 参数

<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">跳转</router-link>
				
<!-- 跳转并携带query参数,to的对象写法(推荐) -->
<router-link 
	:to="{
		path:'/home/message/detail',
		query:{
		   id: m.id,
       title: m.title
		}
	}"
>跳转</router-link>
1
2
3
4
5
6
7
8
9
10
11
12
13

接收

$route.query.id
$route.query.title
1
2