vue router 实现
Vue Router 的实现
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的核心实现方式。
安装 Vue Router
通过 npm 或 yarn 安装 Vue Router:
npm install vue-router
基本配置
在 Vue 项目中引入并配置 Vue Router:
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({
routes
})
export default router
路由视图
在根组件中使用 <router-view> 渲染匹配的组件:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
导航链接
使用 <router-link> 实现导航:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
动态路由
通过冒号 : 定义动态路由参数:
const routes = [
{ path: '/user/:id', component: User }
]
在组件中通过 this.$route.params.id 访问参数。
嵌套路由
通过 children 属性实现嵌套路由:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
编程式导航
通过 this.$router.push 或 this.$router.replace 实现编程式导航:
this.$router.push('/about')
this.$router.replace('/about')
路由守卫
通过路由守卫控制导航行为:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
懒加载路由
通过动态导入实现路由懒加载:
const routes = [
{ path: '/about', component: () => import('./views/About.vue') }
]
命名路由
通过 name 属性为路由命名:
const routes = [
{ path: '/user/:id', name: 'user', component: User }
]
使用命名路由导航:
this.$router.push({ name: 'user', params: { id: 123 } })
路由模式
Vue Router 支持 hash 和 history 两种模式:
const router = new VueRouter({
mode: 'history',
routes
})
滚动行为
通过 scrollBehavior 控制页面滚动行为:
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
},
routes
})






