实现自己的 vue-router

简介: 实现自己的 vue-router

需求分析

  • 作为一个插件存在:实现VueRouter类和install方法
  • 实现两个全局组件:router-view用于显示匹配组件内容,router-link用于跳转
  • 监控url变化:监听hashchange或popstate事件
  • 响应最新url:创建一个响应式的属性current,当它改变时获取对应组件并显示

实现

  1. 作为一个插件存在
// cvue-router.js
let Vue;
// 1. 实现一个插件:挂载$router
class CVueRouter {
  constructor(options) {
    this.$options = options;
  }
}

CVueRouter.install = function(_Vue) {
  // 保存构造函数在KvueRouter里使用
  Vue = _Vue;
  // 挂载$router
  // 获取根实例中的router选项
  Vue.mixin({
    beforeCreate() {
      // 确保在根实例上挂载
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router;
      }
    }
  })
}

export default CVueRouter;
  1. 监控url变化
// cvue-router.js
class CVueRouter {
  constructor(options) {
    this.$options = options;

    // 需要创建响应式的current属性
    Vue.util.defineReactive(this, 'current', '/');
    // this.current = '/';

    // 监控url变化
    window.addEventListener('hashchange', this.onHashChange.bind(this));
    window.addEventListener('load', this.onHashChange.bind(this));
  }
  onHashChange() {
    console.log(window.location.hash)
    this.current = window.location.hash.slice(1);
  }
}
  1. 实现两个全局组件:router-view用于显示匹配组件内容,router-link用于跳转
CVueRouter.install = function(_Vue) {
  //...
  Vue.component('router-link', {
    props: {
      to: {
        type: String,
        required: true
      },
    },
    // 此处不能使用template,因为运行时没有编译器
    render(h) {
      // <a href="#/about">abc</a>
      // <router-link to="/about">
      // h(tag, data, children)
      return h('a', { attrs: { href: '#' + this.to }}, this.$slots.default)
    }
  });
  Vue.component('router-view', {
    render(h) {
      // 获取path对应的Component
      let component = null;
      this.$router.$options.routes.forEach(route => {
        if (route.path === this.$router.current) {
          component = route.component;
        }
      })
      return h(component)
    }
  });
}
  1. 使用路由映射优化
// cvue-router.js
class CVueRouter {
  constructor(options) {
    // ...
    // 创建一个路由映射表
    this.routeMap = {};
    options.routes.forEach(route => {
      this.routeMap[route.path] = route;
    });
  }
}
// cvue-view.js
export default {
  // 因为render中引用了current,所以当current有变化时render函数会被重新调用
  render(h) {
    // 获取path对应的Component
    // let component = null;
    // this.$router.$options.routes.forEach(route => {
    //   if (route.path === this.$router.current) {
    //     component = route.component;
    //   }
    // })

    const { routeMap, current } = this.$router;
    const component = routeMap[current].component || null;
    return h(component);
  }
};
  1. 处理嵌套路由
// cvue-router.js
class CVueRouter {
  constructor(options) {
    this.$options = options;

    // 需要创建响应式的current属性
    // Vue.util.defineReactive(this, 'current', '/');
    this.current = window.location.hash.slice(1) || '/';
    Vue.util.defineReactive(this, 'matched', []);
    // match方法可以递归遍历路由表,获得匹配关系数组
    this.match();

    // 监控url变化
    window.addEventListener('hashchange', this.onHashChange.bind(this));
    window.addEventListener('load', this.onHashChange.bind(this));
  }
  onHashChange() {
    console.log(window.location.hash)
    this.current = window.location.hash.slice(1);
    this.matched = [];
    this.match();
  }
  match(routes) {
    routes = routes || this.$options.routes;
    // 递归遍历
    for (const route of routes) {
      if (route.path === '/' && this.current === '/') {
        this.matched.push(route)
        return
      }
      if (route.path !== '/' && this.current.indexOf(route.path) != -1) {
        this.matched.push(route)
        if (route.children) {
          this.match(route.children)
        }
        return
      }
    }
  }
}
// crouter-view.js
export default {
  render(h) {
    // 标记当前router-view的深度
    this.$vnode.data.routerView = true;
    let depth = 0;
    let parent = this.$parent;
    while (parent) {
      const vnodeData = parent.$vnode && parent.$vnode.data;
      if (vnodeData) {
        if (vnodeData.routerView) {
          // 如果当前parent是一个router-view
          depth++;
        }
      }
      parent = parent.$parent;
    }
    let component = null;
    const route = this.$router.matched[depth];
    if (route) {
      component = route.component;
    }
    return h(component);
  }
};
相关文章
|
5天前
|
人工智能 JavaScript Linux
【Claude Code 全攻略】终端AI编程助手从入门到进阶(2026最新版)
Claude Code是Anthropic推出的终端原生AI编程助手,支持40+语言、200k超长上下文,无需切换IDE即可实现代码生成、调试、项目导航与自动化任务。本文详解其安装配置、四大核心功能及进阶技巧,助你全面提升开发效率,搭配GitHub Copilot使用更佳。
|
6天前
|
存储 人工智能 自然语言处理
OpenSpec技术规范+实例应用
OpenSpec 是面向 AI 智能体的轻量级规范驱动开发框架,通过“提案-审查-实施-归档”工作流,解决 AI 编程中的需求偏移与不可预测性问题。它以机器可读的规范为“单一真相源”,将模糊提示转化为可落地的工程实践,助力开发者高效构建稳定、可审计的生产级系统,实现从“凭感觉聊天”到“按规范开发”的跃迁。
858 13
|
3天前
|
云安全 安全
免费+限量+领云小宝周边!「阿里云2026云上安全健康体检」火热进行中!
诚邀您进行年度自检,发现潜在风险,守护云上业务连续稳健运行
1166 1
|
5天前
|
人工智能 JavaScript 前端开发
【2026最新最全】一篇文章带你学会Cursor编程工具
本文介绍了Cursor的下载安装、账号注册、汉化设置、核心模式(Agent、Plan、Debug、Ask)及高阶功能,如@引用、@Doc文档库、@Browser自动化和Rules规则配置,助力开发者高效使用AI编程工具。
717 4
|
6天前
|
消息中间件 人工智能 Kubernetes
阿里云云原生应用平台岗位急招,加入我们,打造 AI 最强基础设施
云原生应用平台作为中国最大云计算公司的基石,现全面转向 AI,打造 AI 时代最强基础设施。寻找热爱技术、具备工程极致追求的架构师、极客与算法专家,共同重构计算、定义未来。杭州、北京、深圳、上海热招中,让我们一起在云端,重构 AI 的未来。
|
8天前
|
IDE 开发工具 C语言
【2026最新】VS2026下载安装使用保姆级教程(附安装包+图文步骤)
Visual Studio 2026是微软推出的最新Windows专属IDE,启动更快、内存占用更低,支持C++、Python等开发。推荐免费的Community版,安装简便,适合初学者与个人开发者使用。
982 11
|
5天前
|
存储 人工智能 测试技术
【Claude Skills】从原理到实战的完全指南
Claude Skills通过模块化设计,将AI变为领域专家,实现工作流标准化。它支持指令封装、自动触发与脚本集成,提升复用性与协作效率,适用于个人提效与团队协同,是AI定制化的新范式。
|
11天前
|
存储 JavaScript 前端开发
JavaScript基础
本节讲解JavaScript基础核心知识:涵盖值类型与引用类型区别、typeof检测类型及局限性、===与==差异及应用场景、内置函数与对象、原型链五规则、属性查找机制、instanceof原理,以及this指向和箭头函数中this的绑定时机。重点突出类型判断、原型继承与this机制,助力深入理解JS面向对象机制。(238字)
|
9天前
|
人工智能 Shell 开发工具
Claude Code 2.1.2超详细更新说明,小白也能10分钟上手
Claude Code 2.1.x重磅更新:Shift+Enter换行、Esc+Esc撤销、Ctrl+B后台运行,Skills技能系统全面升级,支持多语言、通配符权限与动态MCP检测,性能提升50%,迭代速度惊人,开发者效率暴涨!
Claude Code 2.1.2超详细更新说明,小白也能10分钟上手

热门文章

最新文章