当前位置:首页 > 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实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="w…

vue实现钟表

vue实现钟表

使用 Vue 实现动态钟表 以下是一个基于 Vue 3 的动态钟表实现方案,包含时分秒指针和数字时间显示。 模板部分 <template> <div class="clock-…

ssh vue 实现

ssh vue 实现

使用SSH连接Vue项目部署的服务器 在Vue项目开发或部署过程中,可能需要通过SSH连接到远程服务器进行配置或维护。以下是实现SSH连接并部署Vue项目的关键步骤: 生成SSH密钥对 在本地终端运…

vue实现删除

vue实现删除

Vue 实现删除功能的方法 在 Vue 中实现删除功能通常涉及以下几个步骤: 数据绑定与列表渲染 使用 v-for 指令渲染列表数据,并为每个项绑定唯一标识符(如 id)。例如: <ul…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FFm…

vue实现前端

vue实现前端

Vue 实现前端的核心方法与步骤 安装 Vue 项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 是传统构建工具,Vite 是新一代轻量级工具。 npm init vue@la…