写在前面的话:
1.路由在使用并不是简单的path"/",component{},如果只是这样对router的理解还不够,要知道为什么出现,对比传统的url有什么好处 为什么要写router-view以及routerlink这些
2.**要自己动手搭建路由系统,而不是用现成搭建好的去单独的写页面跳转
Vue Router 核心知识详解(零基础适用)
什么是"路由"?为什么 Vue 需要它?
大白话解释:
"路由"其实就是网址和页面的映射关系。
📌 类比说明:
你打开 /home
显示首页,打开 /about
显示关于页。路由就像一本字典,告诉 Vue:
"如果用户访问
/about
,就展示 About 页面"
📌 在 Vue 中,我们是一个页面(SPA)里切换多个组件,并不真正跳转网页。这就需要 Vue Router 来"接管"浏览器地址栏,并切换对应组件。
✅ 路由的三大基本概念
概念 | 说明 | 举例 |
---|---|---|
路由配置 | 告诉系统"哪个地址显示哪个组件" | /home 显示 Home.vue |
路由出口 <router-view> |
页面实际渲染组件的地方 | 显示区域 |
路由入口 <router-link> |
用户点击跳转的按钮 | 导航菜单 |
🛠 配置路由的全过程
1️⃣ 第一步:项目创建时勾选 Router
vue create my-project
勾选 Router
,Vue 会自动给你生成 src/router/index.js
2️⃣ 第二步:理解 router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', redirect: '/home' }, // 根路径跳转到首页
{ path: '/home', component: Home }, // 配置 home 页
{ path: '/about', component: About } // 配置 about 页
]
const router = new VueRouter({
mode: 'history', // 不带 # 的网址
routes
})
export default router
🖼 页面怎么"显示"出来?
🔍 为什么 <router-view>
是必须的?
你虽然配置了 /about
对应 About.vue
,但还得告诉 Vue:
"页面该放在哪儿?"
这就是 <router-view>
的作用。
📌 示例:
<template>
<div>
<HeaderBar />
<router-view></router-view> <!-- 路由组件的"容器" -->
</div>
</template>
🧭 路由怎么"跳转"?
方法 1:使用 <router-link>
<router-link to="/home">首页</router-link>
<router-link to="/about">关于我们</router-link>
特点:自动生成 <a>
标签,支持高亮激活。
方法 2:JS 编程式跳转
this.$router.push('/about')
你可以写在 methods
里,点击按钮触发。
📌 常用于:
- 表单提交后跳转
- 动态跳转(如:跳去某个 ID 的详情页)
🔢 动态路由参数::id
是什么意思?
场景举例:
比如你有一个用户页面 /user/1
,里面显示 ID 为 1 的用户信息。
你不能为每个用户写一个路径 /user/1
、/user/2
...,所以用动态路由:
{ path: '/user/:id', component: UserPage }
访问 /user/42
,就能在组件里用:
this.$route.params.id // 得到 "42"
❓什么是查询参数(?name=vue)
不是通过路径,而是通过地址栏的 ? 传数据:
this.$router.push({
path: '/search',
query: { keyword: 'vue3' }
})
跳转后地址变成:
/search?keyword=vue3
页面读取:
this.$route.query.keyword
✅ 通常用于:搜索条件、筛选参数等
🔀 嵌套路由(页面内套页面)
比如 /user/profile
、/user/setting
都属于"用户中心"页里的子页面。
配置如下:
{
path: '/user',
component: UserLayout, // 外框
children: [
{ path: 'profile', component: ProfilePage },
{ path: 'setting', component: SettingPage }
]
}
在 UserLayout.vue
里也要加:
<router-view></router-view>
🏷 命名路由(更稳定的跳转方式)
{ path: '/about', name: 'AboutPage', component: About }
跳转方式变成:
this.$router.push({ name: 'AboutPage' })
📌 优点:即使路径变了,name
不变,跳转仍然生效。
🚧 路由守卫(权限控制、拦截)
使用场景:
-
用户没登录,不能进首页;
-
没权限不能访问某些功能页;
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token')
if (to.path !== '/login' && !token) {
next('/login') // 强制跳转登录页
} else {
next() // 放行
}
})
🧱 补充:路由跳转的常用写法对比
功能 | 写法 | 说明 |
---|---|---|
页面链接 | <router-link to="/home"> |
静态跳转 |
JS 跳转 | this.$router.push('/about') |
动态场景下用 |
动态路径 | /user/:id + params.id |
路径带变量 |
查询跳转 | ?keyword=vue |
搜索类页面常用 |
命名跳转 | { name: 'xxx' } |
推荐方式,路径变了也不怕 |
✅ 总结重点(路由小口诀)
路由映射靠配置
router-view 是窗口
router-link 是按钮
路径带 :id 能传参
query 用 ?keyword=xxx
守卫拦路是保安
编程跳转看 push
命名跳转更保险