vue router实现方式
Vue Router 实现方式
Vue Router 是 Vue.js 官方提供的路由管理器,用于构建单页面应用(SPA)。以下是常见的实现方式:
安装 Vue Router
通过 npm 或 yarn 安装 Vue Router:
npm install vue-router
或
yarn add vue-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(),
routes
})
export default router
路由模式
Vue Router 支持两种路由模式:
- Hash 模式:URL 中带有
#符号 - History 模式:需要服务器配置支持
// Hash 模式
createWebHashHistory()
// History 模式
createWebHistory()
路由导航
在组件中使用 <router-link> 进行导航:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
编程式导航:
// 字符串路径
router.push('/about')
// 带查询参数
router.push({ path: '/about', query: { id: 1 } })
// 命名路由
router.push({ name: 'About' })
动态路由
通过冒号 : 定义动态路由参数:
{
path: '/user/:id',
component: User
}
在组件中访问参数:
const route = useRoute()
console.log(route.params.id)
嵌套路由
使用 children 属性定义嵌套路由:
{
path: '/user',
component: User,
children: [
{
path: 'profile',
component: Profile
},
{
path: 'settings',
component: Settings
}
]
}
路由守卫
实现导航守卫来控制路由跳转:
router.beforeEach((to, from, next) => {
// 逻辑处理
next()
})
router.afterEach((to, from) => {
// 逻辑处理
})
懒加载路由
使用动态导入实现路由懒加载:
{
path: '/about',
component: () => import('../views/About.vue')
}
路由元信息
通过 meta 字段添加路由元信息:
{
path: '/admin',
meta: { requiresAuth: true }
}
在导航守卫中使用:

router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
这些实现方式涵盖了 Vue Router 的核心功能,可以根据项目需求选择适合的配置方式。






