在 Vue 中,vue-router
是官方的路由管理插件,用于在单页面应用(SPA)中实现不同页面的切换。在此介绍 Vue 2 和 Vue 3 中路由的使用。
vue-router
如果是 Vue 2:
npm install vue-router@3
如果是 Vue 3:
npm install vue-router@4
创建 router/index.js
作为路由配置文件。
Vue 2
# 路由文件
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: '/', component: Home },
{ path: '/about', component: About }
];
# 创建路由实例
const router = new VueRouter({
mode: 'history', // 使用 history 模式,去掉 URL 中的 #
routes
});
export default router;
Vue 3
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
main.js
中注册路由Vue 2
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
# 挂载根实例
new Vue({
router, // 挂载路由
render: h => h(App)
}).$mount('#app');
Vue 3
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
App.vue
中添加路由出口
用于创建路由导航,to
属性指定跳转路径。
是路由出口,显示当前匹配的组件。const routes = [
{ path: '/user/:id', component: User }
];
User.vue
组件中获取动态参数
用户 ID:{{ $route.params.id }}
Vue 3 Composition API
const routes = [
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home }
];
const routes = [
{ path: '/home', component: Home, alias: '/index' }
];
这样访问 /index
也会展示 Home
组件。
Vue 的 路由守卫(Navigation Guards) 主要用于在路由跳转前后执行特定逻辑,比如:
✅ 权限控制(如登录验证)
✅ 数据预加载(在进入页面前获取数据)
✅ 路由切换时的动画或离开提示
✅ 记录用户访问路径(比如保存上一次访问的页面)
Vue Router 提供了三种类型的守卫:
守卫类型 | 作用范围 | 触发时机 |
---|---|---|
全局守卫 | 作用于所有路由 | 路由跳转前后 |
路由独享守卫 | 作用于某个特定路由 | 进入该路由前 |
组件内守卫 | 作用于某个组件 | 进入、更新、离开该组件时 |
beforeEach
(全局前置守卫)用于 拦截导航,一般用于 登录权限校验。
router.beforeEach((to, from, next) => {
console.log('全局前置守卫:', to.path);
if (to.meta.requiresAuth && !localStorage.getItem('token')) {
next('/login'); // 未登录,跳转到登录页
} else {
next(); // 继续路由跳转
}
});
next()
说明:
next()
继续导航next(false)
取消导航next('/login')
跳转到指定路径beforeResolve
(全局解析守卫)Vue 2.5+ 新增,在 beforeEach
和 beforeEnter
之后执行,所有组件内守卫执行前触发,用于等待异步数据加载完成。
router.beforeResolve((to, from, next) => {
console.log('全局解析守卫:', to.path);
next();
});
afterEach
(全局后置守卫)用于 记录访问路径、切换页面标题等,不会影响路由跳转。
router.afterEach((to, from) => {
console.log('全局后置守卫:', to.path);
document.title = to.meta.title || '默认标题';
});
作用于单个路由,只在进入该路由时触发。
const routes = [
{
path: '/profile',
component: Profile,
beforeEnter: (to, from, next) => {
console.log('路由独享守卫:进入 /profile');
next();
}
}
];
作用于某个组件,通常用于 数据加载、离开前确认。
beforeRouteEnter
进入组件前触发,不能访问 this
,因为组件还没创建。
beforeRouteUpdate
(Vue 2.2+)当 路径相同但参数变化时触发,适用于 监听动态路由参数变化(如 /user/:id
)。
beforeRouteLeave
离开组件前触发,通常用于 确认框。
守卫 | 作用 | 适用场景 |
---|---|---|
beforeEach |
全局前置守卫 | 登录校验、全局数据预加载 |
beforeResolve |
全局解析守卫 | 组件内守卫执行前,确保异步数据加载完成 |
afterEach |
全局后置守卫 | 记录访问路径、修改页面标题 |
beforeEnter |
路由独享守卫 | 进入某个特定路由前检查 |
beforeRouteEnter |
组件内守卫(进入前) | 进入组件前获取数据(不能访问 this ) |
beforeRouteUpdate |
组件内守卫(更新时) | 监听动态参数变化 |
beforeRouteLeave |
组件内守卫(离开时) | 页面离开前弹出确认框 |
const routes = [
{ path: '/about',
component: () => import('../views/About.vue')
}
];
这样 About.vue
只有在访问 /about
时才会加载,提高首屏加载速度。
hash
模式(默认模式)hash
模式的 URL 以 #
开头,例如:
http://example.com/#/about
✅ 无需后端配置,兼容性好。
❌ #
号对 SEO 不友好。
Vue 2
const router = new VueRouter({
mode: 'hash',
routes
});
Vue 3
const router = createRouter({
history: createWebHashHistory(),
routes
});
history
模式history
模式使用 HTML5 History API,使 URL 看起来更干净,例如:
http://example.com/about
✅ URL 结构清晰,没有 #
号,对 SEO 友好。
❌ 需要后端支持,否则刷新页面会 404。
Vue 2
const router = new VueRouter({
mode: 'history',
routes
});
Vue 3
const router = createRouter({
history: createWebHistory(),
routes
});
后端配置(Nginx)
location / {
try_files $uri /index.html;
}
如果使用 history
模式,一定要配置服务器,否则刷新时会返回 404。
abstract
模式abstract
模式不会在 URL 中展示路由信息,适用于 无浏览器环境(如 SSR)。
✅ 适用于服务器端渲染(SSR)或测试环境。
❌ 不能在普通浏览器中直接使用。
Vue 2
const router = new VueRouter({
mode: 'abstract',
routes
});
Vue 3 不支持 abstract
模式,因为它主要用于 SSR,而 Vue 3 推荐使用 Nuxt.js 进行服务器端渲染。
模式 | 适用场景 | SEO 友好 | 需要服务器配置 | URL 形式 |
---|---|---|---|---|
hash |
适用于所有浏览器 | ❌ | ❌ | http://example.com/#/about |
history |
SEO 友好的 SPA | ✅ | ✅ | http://example.com/about |
abstract |
SSR 或测试环境 | ❌ | ❌ | 不展示 URL |
在大多数情况下:
hash
,无需配置后端。history
,但要配合服务器设置。abstract
,但 Vue 3 一般使用 Nuxt 进行 SSR 处理。用户详情
获取:
this.$route.params.id;
用户详情
获取:
this.$route.query.id;
props
传参在 router/index.js
中启用 props
const routes = [
{ path: '/user/:id', component: User, props: true }
];
在 User.vue
组件中直接使用 props
keep-alive
保持组件状态某些情况下,我们希望组件在切换时保持状态,而不是每次都重新加载。
这样,当用户切换回来时,组件不会重新创建,而是保留之前的状态。