vue路由实现和原理
Vue 路由的实现方式
基于 vue-router 的配置
安装 vue-router 后,通过 Vue.use() 注册插件。定义路由表(routes)并创建 router 实例,注入到 Vue 根实例中。
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './views/Home.vue';
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: () => import('./views/About.vue') }
];
const router = new VueRouter({
routes
});
new Vue({
router,
render: h => h(App)
}).$mount('#app');
动态路由与参数传递
通过 : 定义动态路径参数,组件内通过 this.$route.params 访问。
{ path: '/user/:id', component: User }
嵌套路由
使用 children 属性定义嵌套路由结构,父组件需包含 <router-view>。
{
path: '/parent',
component: Parent,
children: [
{ path: 'child', component: Child }
]
}
Vue 路由的核心原理
Hash 模式与 History 模式
- Hash 模式:利用 URL 的
#部分(如http://example.com/#/path),通过监听hashchange事件实现路由切换。兼容性强,无需服务器配置。 - History 模式:基于 HTML5 History API(
pushState/replaceState),URL 无#(如http://example.com/path)。需服务器支持,避免直接访问子路径时 404。
路由切换流程
- 用户点击
<router-link>或调用this.$router.push()。 - 路由实例根据路径匹配路由表,获取目标组件。
- 触发导航守卫(如
beforeEach),确认后更新视图。 - 渲染新组件到
<router-view>,同时更新 URL。
响应式实现
Vue Router 通过将当前路由信息($route)定义为响应式对象,当路径变化时自动触发组件更新。依赖 Vue 的响应式系统,确保视图与 URL 同步。
导航守卫的应用
全局守卫
router.beforeEach:在导航前执行,可用于权限验证。router.afterEach:导航完成后执行,适合日志记录。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) next('/login');
else next();
});
组件内守卫
beforeRouteEnter:组件渲染前调用。beforeRouteUpdate:当前路由改变但组件复用时调用。beforeRouteLeave:离开路由前调用,可阻止导航。
export default {
beforeRouteLeave(to, from, next) {
if (unsavedChanges) {
if (confirm('Leave without saving?')) next();
} else next();
}
};
路由懒加载优化
通过动态导入(import())实现代码分割,减少初始加载体积。
const About = () => import('./views/About.vue');
结合 Webpack 的魔法注释可命名 chunk:
const About = () => import(/* webpackChunkName: "about" */ './views/About.vue');






