We often involve the introduction of plug-ins when using Vue. Use (plug-in), which is actually called the install method of the plug-in and passed in the Vue instance as a parameter. Let’s first review the use of vue-Router in the project

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '.. /views/Home.vue'
VueRouter is a plugin for VueRouter
Vue.use(VueRouter)

// 2. Declare a routing table
const routes = [
 {
   path: '/'.name: 'Home'.component: Home
 }
]

Create a Router instance
const router = new VueRouter({
 routes
})

export default router


//App.vue
<router-view></router-view>
/ / navigation
<router-link to="/">Home</router-link>
Copy the code

Use (VueRouter); create a routing table, instantiate VueRouter, and pass in the routing table as a parameter.

1. Implement VueRouter class and install method
2. Implement two global components: router-View and router-link
3. Listen for URL changes: For now, use hashchange
4, view update: for URL update for the component corresponding display

Without further ado, go to the code

// Implement a plug-in
// Return a function
// Or return an object that has an install method
let _Vue

class VueRouter {
// option: routes - Routing table
constructor(options) {
 this.$options = options

 // Cache path and route mappings
 this.routeMap = {}
 this.$options.routes.forEach(
   route= > {
     this.routeMap[route.path] = route
   })
 // console.log(route);
 
 // A reactive current attribute needs to be defined
 const initial = window.location.hash.slice(1) | |'/'
 _Vue.util.defineReactive(this.'current', initial)
 

 // Monitor URL changes
 window.addEventListener('hashchange'.this.onHashChange.bind(this))}onHashChange() {
 
 // Just the part after #
 this.current = window.location.hash.slice(1)
 console.log(this.current);
 
}
}


VueRouter.install = function(Vue) {
// Reference the Vue constructor, used in VueRouter above
_Vue = Vue

1. Mount $router
Vue.mixin({
 beforeCreate() {
   // This refers to the component instance
   if (this.$options.router) {
     Vue.prototype.$router = this.$options.router
   }
 }
})

// 2. Define two global components, router-link and router-view
Vue.component('router-link', {
 // template: '<a>'
 props: {
   to: {
     type: String.require: true}},render(h) {
   // <router-link to="/about">
   // <a href="#/about">xxx</a>
   // return <a href={'#'+this.to}>{this.$slots.default}</a>
   return h('a', {
     attrs: {
       href: The '#' + this.to
     }
   }, this.$slots.default)
 }
})
Vue.component('router-view', {
 render(h) {
   // Find the component corresponding to the current URL
   const {routeMap, current} = this.$router
   const component = routeMap[current] ? routeMap[current].component : null
   // Render the incoming component
   return h(component)
 }
})
}

export default VueRouter
Copy the code

Interested children can delve into the source github.com/vuejs/vue-r…