vue中vue-router的实现原理

plugins/vue-router.js文件中

// 1.创建一个VueRouter类

import { h } from "vue";
let Vue;
class VueRouter {
  constructor(options) {
    this.$options = options;
    // this.current = location.hash.slice(1) || ''
    // 定义一个响应式的current属性
    // console.log(location.hash);
    Vue.util.defineReactive(this, 'current', location.hash.slice(1) || '')
    // 监听hash值的变化
    window.addEventListener('hashchange', () => {
      this.current = location.hash.slice(1)
    })
    this.routesMap = {}
    // 将routes中的path和component做一个映射
    this.$options.routes.forEach(item => {
      this.routesMap[item.path] = item.component
    })
  }
}


// 2.只要是vue的插件,都要实现一个install方法


// install方法第一个参数:Vue构造函数,第二个参数是可选的,调用use方法时传递的第二个参数
VueRouter.install = function(_Vue, options) {
  Vue = _Vue;

  // 利用vue的混入--->mixin
  // 利用混入,将挂载router实例的这段代码延迟到vue实例创建完毕之后执行
  Vue.mixin({
    beforeCreate() {
      // 判断当前属性上是否具有router属性,避免每一个组件都执行一遍
      if(this.$options.router) {
        Vue.prototype.$router = this.$options.router
      }
    }
  })

// 3.注册两个全局组件router-link 和 router-view

  // router-link组件
  Vue.component('router-link', {
    render(h) {
      return h('a', { attrs: { href: '#' + this.to } }, this.$slots.default)
    }
  })
  // router-view组件
  Vue.component('router-view', {
    render() {
      const path = this.$router.current;
      const component = this.$router.routesMap[path];
      return h(component)
    }
  })
}

export default VueRouter;

router/index.js 文件

import Vue from 'vue'
import VueRouter from '../plugins/vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

// 前端路由:url 和 组件的对应关系
const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
  }
]

const router = new VueRouter({
  // mode: 'history', vue-router@3
  routes
})

export default router
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚时之秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值