如何手写简易的 Vue Router

前言

还是那样,懂得如何使用一个常用库,还得了解其原理或者怎么模拟实现,今天实现一下 vue-router 。

有一些知识我这篇文章提到了,这里就不详细一步步写,请看我 手写一个简易的 Vuex

基本骨架

  • Vue 里面使用插件的方式是 Vue.use(plugin) ,这里贴出它的用法:

安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象。

  • 全局混入

使用 Vue.mixin(mixin)

全局注册一个混入,影响注册之后所有创建的每个 Vue 实例。可以使用混入向组件注入自定义的行为,它将影响每一个之后创建的 Vue 实例。

  • 路由用法

比如简单的:

// 路由数组
const routes = [
 {
  path: '/',
  name: 'Page1',
  component: Page1,
 },
 {
  path: '/page2',
  name: 'Page2',
  component: Page2,
 },
]

const router = new VueRouter({
 mode: 'history', // 模式
 routes,
})

它是传入了moderoutes,我们实现的时候需要在VueRouter构造函数中接收。

在使用路由标题的时候是这样:

<p>
 <!-- 使用 router-link 组件来导航. -->
 <!-- 通过传入 `to` 属性指定链接. -->
 <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
 <router-link to="/page1">Go to Foo</router-link>
 <router-link to="/page2">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>

故我们需要使用Vue.component( id, [definition] )注册一个全局组件。

了解了大概,我们就可以写出一个基本骨架

let Vue = null

class VueRouter {
 constructor(options) {
  this.mode = options.mode || 'hash'
  this.routes = options.routes || []
 }
}

VueRouter.install = function (_Vue) {
 Vue = _Vue

 Vue.mixin({
  beforeCreate() {
   // 根组件
   if (this.$options && this.$options.router) {
    this._root = this // 把当前vue实例保存到_root上
    this._router = this.$options.router // 把router的实例挂载在_router上
   } else if (this.$parent && this.$parent._root) {
    // 子组件的话就去继承父组件的实例,让所有组件共享一个router实例
    this._root = this.$parent && this.$parent._root
   }
  },
 })

 Vue.component('router-link', {
  props: {
   to: {
    type: [String, Object],
    required: true,
   },
   tag: {
    type: String,
    default: 'a', // router-link 默认渲染成 a 标签
   },
  },
  render(h) {
   let tag = this.tag || 'a'
   return <tag href={this.to}>{this.$slots.default}</tag>
  },
 })

 Vue.component('router-view', {
  render(h) {
   return h('h1', {}, '视图显示的地方') // 暂时置为h1标签,下面会改
  },
 })
}

export default VueRouter

mode

vue-router有两种模式,默认为 hash 模式。

history 模式

通过window.history.pushStateAPI 来添加浏览器历史记录,然后通过监听popState事件,也就是监听历史记录的改变,来加载相应的内容。

  • popstate 事件

当活动历史记录条目更改时,将触发 popstate 事件。如果被激活的历史记录条目是通过对 history.pushState()的调用创建的,或者受到对 history.replaceState()的调用的影响,popstate 事件的 state 属性包含历史条目的状态对象的副本。

  • History.pushState()方法

window.history.pushState(state, title, url)

该方法用于在历史中添加一条记录,接收三个参数,依次为:

  • state:一个与添加的记录相关联的状态对象,主要用于popstate事件。该事件触发时,该对象会传入回调函数。也就是说,浏览器会将这个对象序列化以后保留在本地,重新载入这个页面的时候,可以拿到这个对象。如果不需要这个对象,此处可以填null。
  • title:新页面的标题。但是,现在所有浏览器都忽视这个参数,所以这里可以填空字符串。
  • url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。

hash 模式

使用 URL 的 hash 来模拟一个完整的 URL。,通过监听hashchange事件,然后根据hash值(可通过 window.location.hash 属性读取)去加载对应的内容的。

继续增加代码,

let Vue = null

class HistoryRoute {
 constructor() {
  this.current = null // 当前路径
 }
}

class VueRouter {
 constructor(options) {
  this.mode = options.mode || 'hash'
  this.routes = options.routes || []
  this.routesMap = this.createMap(this.routes)
  this.history = new HistoryRoute() // 当前路由
  this.initRoute() // 初始化路由函数
 }

 createMap(routes) {
  return routes.reduce((pre, current) => {
   pre[current.path] = current.component
   return pre
  }, {})
 }

 initRoute() {
  if (this.mode === 'hash') {
   // 先判断用户打开时有没有hash值,没有的话跳转到 #/
   location.hash ? '' : (location.hash = '/')
   window.addEventListener('load', () => {
    this.history.current = location.hash.slice(1)
   })
   window.addEventListener('hashchange', () => {
    this.history.current = location.hash.slice(1)
   })
  } else {
   // history模式
   location.pathname ? '' : (location.pathname = '/')
   window.addEventListener('load', () => {
    this.history.current = location.pathname
   })
   window.addEventListener('popstate', () => {
    this.history.current = location.pathname
   })
  }
 }
}

VueRouter.install = function (_Vue) {
 Vue = _Vue

 Vue.mixin({
  beforeCreate() {
   if (this.$options && this.$options.router) {
    this._root = this
    this._router = this.$options.router
    Vue.util.defineReactive(this, '_route', this._router.history) // 监听history路径变化
   } else if (this.$parent && this.$parent._root) {
    this._root = this.$parent && this.$parent._root
   }
   // 当访问this.$router时即返回router实例
   Object.defineProperty(this, '$router', {
    get() {
     return this._root._router
    },
   })
   // 当访问this.$route时即返回当前页面路由信息
   Object.defineProperty(this, '$route', {
    get() {
     return this._root._router.history.current
    },
   })
  },
 })
}

export default VueRouter

router-link 和 router-view 组件

VueRouter.install = function (_Vue) {
 Vue = _Vue

 Vue.component('router-link', {
  props: {
   to: {
    type: [String, Object],
    required: true,
   },
   tag: {
    type: String,
    default: 'a',
   },
  },
  methods: {
   handleClick(event) {
    // 阻止a标签默认跳转
    event && event.preventDefault && event.preventDefault()
    let mode = this._self._root._router.mode
    let path = this.to
    this._self._root._router.history.current = path
    if (mode === 'hash') {
     window.history.pushState(null, '', '#/' + path.slice(1))
    } else {
     window.history.pushState(null, '', path.slice(1))
    }
   },
  },
  render(h) {
   let mode = this._self._root._router.mode
   let tag = this.tag || 'a'
   let to = mode === 'hash' ? '#' + this.to : this.to
   console.log('render', this.to)
   return (
    <tag on-click={this.handleClick} href={to}>
     {this.$slots.default}
    </tag>
   )
   // return h(tag, { attrs: { href: to }, on: { click: this.handleClick } }, this.$slots.default)
  },
 })

 Vue.component('router-view', {
  render(h) {
   let current = this._self._root._router.history.current // current已经是动态响应
   let routesMap = this._self._root._router.routesMap
   return h(routesMap[current]) // 动态渲染对应组件
  },
 })
}

至此,一个简易的vue-router就实现完了,案例完整代码附上:

let Vue = null

class HistoryRoute {
 constructor() {
  this.current = null
 }
}

class VueRouter {
 constructor(options) {
  this.mode = options.mode || 'hash'
  this.routes = options.routes || []
  this.routesMap = this.createMap(this.routes)
  this.history = new HistoryRoute() // 当前路由
  // 初始化路由函数
  this.initRoute()
 }

 createMap(routes) {
  return routes.reduce((pre, current) => {
   pre[current.path] = current.component
   return pre
  }, {})
 }

 initRoute() {
  if (this.mode === 'hash') {
   // 先判断用户打开时有没有hash值,没有的话跳转到 #/
   location.hash ? '' : (location.hash = '/')
   window.addEventListener('load', () => {
    this.history.current = location.hash.slice(1)
   })
   window.addEventListener('hashchange', () => {
    this.history.current = location.hash.slice(1)
   })
  } else {
   // history模式
   location.pathname ? '' : (location.pathname = '/')
   window.addEventListener('load', () => {
    this.history.current = location.pathname
   })
   window.addEventListener('popstate', () => {
    this.history.current = location.pathname
   })
  }
 }
}

VueRouter.install = function(_Vue) {
 Vue = _Vue

 Vue.mixin({
  beforeCreate() {
   // 根组件
   if (this.$options && this.$options.router) {
    this._root = this // 把当前vue实例保存到_root上
    this._router = this.$options.router // 把router的实例挂载在_router上
    Vue.util.defineReactive(this, '_route', this._router.history) // 监听history路径变化
   } else if (this.$parent && this.$parent._root) {
    // 子组件的话就去继承父组件的实例,让所有组件共享一个router实例
    this._root = this.$parent && this.$parent._root
   }
   // 当访问this.$router时即返回router实例
   Object.defineProperty(this, '$router', {
    get() {
     return this._root._router
    },
   })
   // 当访问this.$route时即返回当前页面路由信息
   Object.defineProperty(this, '$route', {
    get() {
     return this._root._router.history.current
    },
   })
  },
 })

 Vue.component('router-link', {
  props: {
   to: {
    type: [String, Object],
    required: true,
   },
   tag: {
    type: String,
    default: 'a',
   },
  },
  methods: {
   handleClick(event) {
    // 阻止a标签默认跳转
    event && event.preventDefault && event.preventDefault() // 阻止a标签默认跳转
    let mode = this._self._root._router.mode
    let path = this.to
    this._self._root._router.history.current = path
    if (mode === 'hash') {
     window.history.pushState(null, '', '#/' + path.slice(1))
    } else {
     window.history.pushState(null, '', path.slice(0))
    }
   },
  },
  render(h) {
   let mode = this._self._root._router.mode
   let tag = this.tag || 'a'
   let to = mode === 'hash' ? '#' + this.to : this.to
   return (
    <tag on-click={this.handleClick} href={to}>
     {this.$slots.default}
    </tag>
   )
   // return h(tag, { attrs: { href: to }, on: { click: this.handleClick } }, this.$slots.default)
  },
 })

 Vue.component('router-view', {
  render(h) {
   let current = this._self._root._router.history.current // current已经是动态
   let routesMap = this._self._root._router.routesMap
   return h(routesMap[current]) // 动态渲染对应组件
  },
 })
}

export default VueRouter

ps: 个人技术博文 Github 仓库,觉得不错的话欢迎 star,给我一点鼓励继续写作吧~

以上就是如何手写简易的 Vue Router的详细内容,更多关于手写简易的 Vue Router的资料请关注我们其它相关文章!

(0)

相关推荐

  • Vue Router的手写实现方法实现

    为什么需要前端路由 在前后端分离的现在,大部分应用的展示方式都变成了 SPA(单页面应用 Single Page Application)的模式.为什么会选择 SPA 呢?原因在于: 用户的所有操作都在同一个页面下进行,不进行页面的跳转.用户体验好. 对比多页面,单页面不需要多次向服务器请求加载页面(只请求一次.html文件),只需要向服务器请求数据(多亏了 ajax).因此,浏览器不需要渲染整个页面.用户体验好. 归根结底,还是因为 SPA 能够提供更好的用户体验. 为了更好地实现 SPA,前

  • 解决vue的router组件component在import时不能使用变量问题

    webpack 编译es6 动态引入 import() 时不能传入变量,例如dir ='path/to/my/file.js' : import(dir) , 而要传入字符串 import('path/to/my/file.js'),这是因为webpack的现在的实现方式不能实现完全动态. 但一定要用变量的时候,可以通过字符串模板来提供部分信息给webpack:例如import(./path/${myFile}), 这样编译时会编译所有./path下的模块,但运行时确定myFile的值才会加载,

  • vue-router重写push方法,解决相同路径跳转报错问题

    修改vue-router的配置文件,默认位置router/index.js import Vue from 'vue' import Router from 'vue-router' /** * 重写路由的push方法 * 解决,相同路由跳转时,报错 * 添加,相同路由跳转时,触发watch (针对el-menu,仅限string方式传参,形如"view?id=5") */ // 保存原来的push函数 const routerPush = Router.prototype.push

  • Vue this.$router.push(参数)实现页面跳转操作

    很多情况下,我们在执行点击按钮跳转页面之前还会执行一系列方法,这时可以使用 this.$router.push(location) 来修改 url,完成跳转. push 后面可以是对象,也可以是字符串: // 字符串 this.$router.push('/home/first') // 对象 this.$router.push({ path: '/home/first' }) // 命名的路由 this.$router.push({ name: 'home', params: { userId

  • vue项目使用$router.go(-1)返回时刷新原来的界面操作

    在项目需求中,我们常常需要使用$router.go(-1)返回之前的页面,但是却发现,之前的界面,保持着上次跳转的状态,比如说:弹框未关闭之类的等等,..... 问题如下: 界面1 : 界面2使用$router.go(-1)返回上一次的界面 由于使用$router.go(-1)返回,导致之前的数据都保留,并未刷新原来的界面,如下:还是显示跳转前的弹框 解决方法1: 不要使用$router.go(-1),而是使用$router.push('某某某'),但是其实这种方法是不合理的,因为你可能跳转的页

  • 解决VUE-Router 同一页面第二次进入不刷新的问题

    最近正好遇到一个问题,修改用户的头像,修改后再进入用户主页,发现改了之后即使数据变了..页面也不会重新渲染... 下面提供几种解决方案来给予大家参考: 1. 可以在刷新的页面定义一个参数, 这样每次都会渲染出不同的页面: route 实例化命名配置: { // 用户信息 path: '/accountDetail/:randKey', name: 'accountDetail', component: accountDetail, meta: {requiresAuth: true} }, 跳转

  • vue-router 控制路由权限的实现

    注意:vue-router是无法完全控制前端路由权限. 1.实现思路 使用vue-router实例函数addRoutes动态添加路由规则,不多废话直接上思维导图: 2.实现步骤 2.1.路由匹配判断 // src/router.js import Vue from 'vue'; import Store from '@/store'; import Router from 'vue-router'; import Cookie from 'js-cookie'; const routers =

  • vue-router之解决addRoutes使用遇到的坑

    最近项目中使用了vue-router的addRoutes这个api,遇到了一个小坑,记录总结一下. 场景复现: 做前端开发的同学,大多都遇到过这种需求:页面菜单根据用户权限动态生成,一个常见的解决方案是: 前端初始化的时候,只挂载不需要权限路由,如登陆,注册等页面路由,然后等用户登录之后,后端返回当前用户的权限表,前端根据这个权限表遍历前端路由表,动态生成用户权限路由,然后使用vue-router提供的addRoutes,将权限路由表动态添加到路由实例中,整个过程大致如下: // router.

  • 解决Vue-Router升级导致的Uncaught (in promise)问题

    在升级了Vue-Router版本到到3.1.0及以上之后,页面在跳转路由控制台会报Uncaught (in promise)的问题 这是什么原因呢? 看vue-router的版本更新日志 V3.1.0版本里面新增功能:push和replace方法会返回一个promise, 你可能在控制台看到未捕获的异常 解决方法一:在调用方法的时候用catch捕获异常 this.$router.replace({ name: 'foo' }).catch(err => { console.log('all go

  • vue-router 按需加载 component: () => import() 报错的解决

    vue的单页面(SPA)项目,必然涉及路由按需的问题. 以前我们是这么做的 //require.ensure是webpack里面的,这样做会将单独拉出来作为一个chunk文件 const Login = r => require.ensure( [], () => r (require('../component/Login.vue'))); 但现在vue-router的官网看看,推荐这种方式: //vue异步组件和webpack的[代码分块点]功能结合,实现了按需加载 const App =

  • 区分vue-router的hash和history模式

    一.概念 为了构建 SPA(单页面应用),需要引入前端路由系统,这也就是 Vue-Router 存在的意义. 前端路由的核心,就在于:改变视图的同时不会向后端发出请求. 为了达到这种目的,浏览器当前提供了以下两种支持: 1.hash--即地址栏 URL 中的 # 符号(此 hash 不是密码学里的散列运算). 比如这个 URL:http://www.abc.com/#/hello,hash 的值为 #/hello. 它的特点在于:hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中

  • 解决vue+router路由跳转不起作用的一项原因

    如下所示: Vue.use(Router) export default new Router({ mode:'history', routes: [ { path: '/', component: Login }, { path: '/login', component: Login }, { path: '/register',component: Register}, {path: '/*', component: NotFound}, ] }) 记得要写上 mode:'history',

随机推荐