1, copy the router folder from the project, name it kRouter and create a new k-rouer.js file

// Own router
// 1. The VueRouter class is a plug-in
let Vue;
class VueRouter {
  constructor(options) {
    this.$options = options;
    Declare a reactive current
    // Render functions must rely on reactive data if they are to be executed repeatedly
    const initial = window.location.hash.slice(1) | |"/";
    Vue.util.defineReactive(this."current", initial);
    // this.current = window.location.hash.slice(1) || '/'
    // Listen for URL changes
    window.addEventListener("hashchange".() = > {
      this.current = window.location.hash.slice(1); }); }}// The plug-in implements install
// Argument 1 is Vue
VueRouter.install = function(_Vue) {
  // Save the constructor reference
  Vue = _Vue;

  // 2. Mount $router to Vue prototype
  // Use global mixin to delay execution of the following code so that the Router instance can be obtained
  Vue.mixin({
    beforeCreate() {
      // This refers to the component instance
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router; }}});// 3. Declare two global components router-view and router-link
  // <router-link to="/abc">xxx</router-link>
  Vue.component("router-link", {
    props: {
      to: {
        type: String.required: true,}},render(h) {
      // <a href="#/abc">xxx</a>
      // This points to the current component instance
      // return <a href={'#'+this.to}>{this.$slots.default}</a>
      return h("a", { attrs: { href: "#" + this.to } }, this.$slots.default); }}); Vue.component("router-view", {
    render(h) {
      // current
      // Get the corresponding component in the routing table according to current and render it
      let component = null;
      const route = this.$router.$options.routes.find(
        (route) = > route.path === this.$router.current
      );
      if (route) {
        component = route.component
      }
      returnh(component); }}); };export default VueRouter;
Copy the code

2. Import to the index.js file of kRouter

import Vue from 'vue'
import VueRouter from './k-rouer'
import Home from '.. /views/Home.vue'
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
Copy the code