vue router怎么实现
Vue Router 实现方法
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页应用(SPA)。以下是实现 Vue Router 的基本步骤和配置方法。
安装 Vue Router
通过 npm 或 yarn 安装 Vue Router:
npm install vue-router
# 或
yarn add vue-router
基本配置
在 Vue 项目中引入并配置 Vue Router:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
});
export default router;
路由视图和导航
在 Vue 应用的入口文件(如 main.js)中引入并挂载路由:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
在模板中使用 <router-view> 和 <router-link>:
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
动态路由
通过冒号 : 定义动态路由参数:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/user/:id', component: User }
]
});
在组件中通过 $route.params 访问参数:
export default {
mounted() {
console.log(this.$route.params.id);
}
}
嵌套路由
通过 children 属性定义嵌套路由:
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
});
在父组件中使用 <router-view> 显示子路由:
<template>
<div>
<h1>User</h1>
<router-view></router-view>
</div>
</template>
路由守卫
通过路由守卫实现权限控制或导航逻辑:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
懒加载路由
使用动态导入实现路由懒加载:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: () => import('./views/Home.vue') },
{ path: '/about', component: () => import('./views/About.vue') }
]
});
命名路由
通过 name 属性为路由命名:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/about', name: 'about', component: About }
]
});
通过名称导航:
<router-link :to="{ name: 'home' }">Home</router-link>
编程式导航
通过 router.push 或 router.replace 实现编程式导航:
this.$router.push('/about');
this.$router.push({ name: 'about' });
this.$router.replace('/login');
路由元信息
通过 meta 字段定义路由元信息:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/admin', component: Admin, meta: { requiresAuth: true } }
]
});
滚动行为
通过 scrollBehavior 控制页面滚动行为:
const router = createRouter({
history: createWebHistory(),
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
return { top: 0 };
}
},
routes: [...]
});
路由模式
Vue Router 支持两种历史模式:

createWebHistory: HTML5 模式(无#)createWebHashHistory: Hash 模式(带#)
import { createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes: [...]
});






