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 Router 并配置路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: () => import('./views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('./views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
routes
})
export default router
路由模式
Vue Router 支持两种路由模式:
hash模式:URL 中带#,兼容性好。history模式:URL 更简洁,需服务器支持。
const router = new VueRouter({
mode: 'history', // 或 'hash'
routes
})
路由导航
在模板中使用 <router-link> 和 <router-view>:

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
编程式导航
通过 this.$router 实现编程式导航:
methods: {
goToHome() {
this.$router.push('/')
},
goToAbout() {
this.$router.push('/about')
}
}
动态路由
配置动态路由参数:
const routes = [
{
path: '/user/:id',
name: 'User',
component: () => import('./views/User.vue')
}
]
在组件中获取参数:

this.$route.params.id
嵌套路由
配置嵌套路由:
const routes = [
{
path: '/user',
component: () => import('./views/User.vue'),
children: [
{
path: 'profile',
component: () => import('./views/Profile.vue')
},
{
path: 'settings',
component: () => import('./views/Settings.vue')
}
]
}
]
路由守卫
使用路由守卫控制导航:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
懒加载路由
通过动态导入实现路由懒加载:
const routes = [
{
path: '/',
component: () => import('./views/Home.vue')
}
]
路由元信息
为路由添加元信息:
const routes = [
{
path: '/admin',
meta: { requiresAuth: true }
}
]
总结
Vue Router 提供了丰富的功能,包括路由配置、导航、动态路由、嵌套路由、路由守卫等。通过合理使用这些功能,可以高效构建单页面应用。






