当前位置:首页 > VUE

自己实现vue-router

2026-02-21 00:18:35VUE

实现基本路由功能

创建路由实例需要管理路由映射关系,并提供核心API。以下代码展示如何初始化路由:

class VueRouter {
  constructor(options) {
    this.routes = options.routes || []
    this.mode = options.mode || 'hash'
    this.routeMap = this.createRouteMap()
    this.current = this.getInitialRoute()

    window.addEventListener('load', () => {
      this.updateView(this.current.path)
    })

    window.addEventListener('hashchange', () => {
      this.current = this.getCurrentRoute()
      this.updateView(this.current.path)
    })
  }
}

创建路由映射表

将路由配置转换为键值对形式便于查找:

createRouteMap() {
  return this.routes.reduce((map, route) => {
    map[route.path] = route.component
    return map
  }, {})
}

获取当前路由

根据不同模式解析当前URL:

getCurrentRoute() {
  let path = ''
  if (this.mode === 'hash') {
    path = window.location.hash.slice(1) || '/'
  } else {
    path = window.location.pathname || '/'
  }
  return { path }
}

视图更新机制

通过响应式数据驱动视图变化:

class VueRouter {
  // ...
  init(app) {
    this.app = app
    defineReactive(this, 'current', this.getCurrentRoute())
  }

  updateView(path) {
    const component = this.routeMap[path] || { template: '<div>Not Found</div>' }
    this.app.currentComponent = component
  }
}

路由安装插件

实现install方法供Vue.use()调用:

VueRouter.install = function(Vue) {
  Vue.mixin({
    beforeCreate() {
      if (this.$options.router) {
        this._router = this.$options.router
        this._router.init(this)
        Vue.util.defineReactive(this, '_route', this._router.current)
      }
    }
  })

  Vue.component('router-link', {
    props: ['to'],
    render(h) {
      return h('a', {
        attrs: { href: '#' + this.to },
        on: { click: this.navigate }
      }, this.$slots.default)
    },
    methods: {
      navigate(e) {
        e.preventDefault()
        window.location.hash = this.to
      }
    }
  })

  Vue.component('router-view', {
    render(h) {
      return h(this._router.routeMap[this._route.path])
    }
  })
}

完整使用示例

在Vue项目中集成自定义路由:

自己实现vue-router

const routes = [
  { path: '/', component: { template: '<div>Home</div>' } },
  { path: '/about', component: { template: '<div>About</div>' } }
]

const router = new VueRouter({
  routes,
  mode: 'hash'
})

new Vue({
  el: '#app',
  router
})

注意事项

实现过程中需要考虑浏览器兼容性、路由守卫、动态路由等高级功能。上述实现提供了核心功能的最小化示例,实际生产环境建议使用官方vue-router。

标签: vuerouter
分享给朋友:

相关文章

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成列…

vue设计与实现下载

vue设计与实现下载

vue设计与实现电子书下载 《Vue.js设计与实现》是一本深入解析Vue.js框架原理的书籍,由霍春阳(HcySunYang)撰写。以下是获取该资源的常见途径: 正版购买渠道 京东、当当、天猫等…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue实现tree

vue实现tree

Vue 实现 Tree 组件 使用 Vue 实现 Tree 组件可以通过递归组件的方式来实现层级结构展示。以下是一个完整的实现方法: 基础递归组件实现 创建 Tree 组件文件 Tree.vue,使…

vue实现addclass

vue实现addclass

Vue 实现动态添加 class 的方法 在 Vue 中动态添加 class 可以通过多种方式实现,以下是常见的几种方法: 使用对象语法 通过绑定一个对象到 :class,可以动态切换 class…

vue遮罩实现

vue遮罩实现

实现 Vue 遮罩的常见方法 使用 CSS 定位和透明度 创建一个全屏遮罩层,通过 CSS 固定定位覆盖整个视口,并设置半透明背景色。 <template> <div cl…