Vue中的路由细节
概念:
关键点在于不刷新界面通过URL变化展示不同组件
实现方式:
Hash模式:URL 中带有 #(如 http://example.com/#/home),# 后的内容作为路由标识,不会发送到服务器
History模式:使用 HTML5 的 history API(pushState/replaceState),URL 无 #(如 http://example.com/home),但需要服务器配置支持
工作原理:
Hash 模式:监听 hashchange 事件,捕获 # 后内容的变化
History 模式:监听 popstate 事件(处理浏览器前进 / 后退),通过 history.pushState 手动修改 URL
核心:
维护一个路由规则表(路由到组件的映射),当 URL 变化时,查找匹配的规则,根据匹配结果,在页面的占位符(如 < router-view >)中渲染对应的组件
现在完成一个简单配置
注意区分routes和router
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'const routes = [{path: '/', // 路径name: 'Home', // 路由名称(可选)component: Home // 对应组件},{path: '/about',name: 'About',component: About}
]const router = createRouter({history: createWebHistory(), // History 模式// history: createWebHashHistory(), // Hash 模式routes//对应上面的routes})export default router
配置完成以后进行路由的跳转
模板中使用声明式跳转
<!-- 普通跳转 -->
<router-link to="/">首页</router-link>
<router-link :to="{ name: 'About' }">关于页</router-link><!-- 带参数 -->
<router-link :to="{ path: '/user', query: { id: 1 } }">用户页</router-link>
JS中使用编程式跳转
import { useRouter } from 'vue-router'
const router = useRouter()// 基本跳转
router.push('/about')
router.push({ name: 'About' })// 带参数
router.push({ path: '/user', params: { id: 1 } }) // params 需配合 name 使用
router.push({ path: '/user', query: { id: 1 } }) // query 会显示在 URL 上// 替换当前历史记录(无回退)
router.replace('/about')
如果我们想要实现局部不刷新的替换
比如说导航栏固定内容区变化
这就是嵌套路由(子路由)
// 配置
{path: '/dashboard',component: Dashboard,children: [{ path: 'profile', component: Profile }, // 子路径:/dashboard/profile{ path: 'settings', component: Settings } // 子路径:/dashboard/settings]
}
模板中需在父组件添加 < router-view > 作为子组件的占位符
当我们需要控制路由跳转权限时需要用到路由守卫
-
全局守卫(影响所有路由):
// 跳转前触发 router.beforeEach((to, from, next) => {// to: 目标路由,from: 来源路由if (to.path === '/admin' && !isLogin) {next('/login') // 未登录则跳转到登录页} else {next() // 允许跳转} })
-
组件内守卫(仅影响当前组件):
export default {beforeRouteEnter(to, from, next) {// 进入组件前调用(此时组件实例未创建)},beforeRouteLeave(to, from, next) {// 离开组件时调用(可用于确认弹窗)if (confirm('确定离开吗?')) {next()}} }
6. 路由懒加载
优化首屏加载速度,按需加载组件:
const routes = [{path: '/about',component: () => import('../views/About.vue') // 懒加载}
]
四、History 模式的服务器配置
History 模式下,直接刷新页面会向服务器请求该 URL,需服务器配置将所有请求转发到 index.html
:
- Nginx 配置:
location / {try_files $uri $uri/ /index.html; }
- Apache 配置:
在.htaccess
中添加:FallbackResource /index.html
前端路由 vs 后端路由
类型 | 工作原理 | 场景 |
---|---|---|
前端路由 | 客户端通过 JS 匹配 URL 并渲染组件 | 单页应用(SPA) |
后端路由 | 服务器根据 URL 返回对应的 HTML 页面 | 多页应用(MPA) |