/**
 * 1、实现并生命了全局注册的组件,分别是router-link、router-view
 * 2、实现install: this.$router.push()
 */

/**
 * vue插件怎么写
 * 1)function/对象
 * 2)要求必须又一个install方法
 */
let Vue; // 保存Vue的构造函数,在插件中使用
class VueRouter {
  constructor(options) {
    this.$options = options
    // 把this.current变为响应式的数据
    // 将来数据一旦发生变化,router-view的render函数能够重新执行
    let initial = window.location.hash.slice(1) || \'/\'
    Vue.util.defineReactive(this, "current", initial)
    window.addEventListener(\'hashchange\', () => {
      this.current = window.location.hash.slice(1) || \'/\'
    })
  }
}

VueRouter.install = (_Vue) => {
  Vue = _Vue
  // 挂载$router属性 this.$router.push
  // 全局混入:(延迟下面的逻辑到router创建完毕,并且附加到选项上时才执行
  Vue.mixin({
    beforeCreate () {
      // 注意此钩子在每个组件创建实例的时候都会调用
      // 根实例才有该选项
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router
      }
    },
  })

  // 实现router-link router-view
  // <router-link to="/">Home</router-link>
  // 转为:<a href="/"></a>
  Vue.component(\'router-link\', {
    props: {
      to: {
        type: String,
        required: true
      }
    },
    render (h) {
      return h(\'a\', {
        attrs: {
          href: `#${this.to}`
        }
      }, this.$slots.default)
    }
  })
  Vue.component(\'router-view\', {
    render (h) {
      let component = null
      // 获取当前路由所对应的组件,并将它渲染出来
      const current = this.$router.current
      const route = this.$router.$options.routes.find(route => route.path === current)
      if (route) {
        component = route.component
      }
      return h(component)
    }
  })
}

export default VueRouter

使用方式

import Vue from \'vue\'
import VueRouter from \'./router\'
import Home from \'../views/Home.vue\'

// 这是一个插件
// 内部做了什么
/**
 * 1、实现并生命了全局注册的组件,分别是router-link、router-view
 * 2、实现install: this.$router.push()
 * 3、
 */
Vue.use(VueRouter)

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({
  routes
})

export default router

版权声明:本文为chinesedon原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/chinesedon/p/15170609.html