当前位置:首页 > 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)
    })
  }
}

创建路由映射表

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

自己实现vue-router

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 }
}

视图更新机制

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

自己实现vue-router

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项目中集成自定义路由:

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实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> &l…

vue实现计算

vue实现计算

Vue 实现计算的方法 在 Vue 中实现计算功能可以通过多种方式完成,主要包括计算属性(computed)、方法(methods)和侦听器(watch)。以下是具体的实现方法: 计算属性(Comp…

vue翻页实现

vue翻页实现

Vue翻页实现方法 基础分页组件实现 使用v-for和计算属性实现基础分页逻辑: <template> <div> <ul> <li…

vue实现甘特图

vue实现甘特图

使用 Vue 实现甘特图 基于开源库(如 vue-ganttastic) 安装依赖库: npm install vue-ganttastic 示例代码: <template> &l…

vue怎么实现onclick

vue怎么实现onclick

在Vue中实现点击事件(类似原生onclick)可以通过多种方式完成,以下是常见方法: 使用 v-on 指令 Vue提供了v-on指令绑定DOM事件,简写为@。例如绑定点击事件: <butt…