Hello, I’m Pan Yongxu. We meet again and today we have an implementation of the VueRouter. Everyone’s praise is the source of power to support me to write the article, I hope to bring different things to you, thank you for your support.

Route configuration && usage

// router.js
import Vue from 'vue'
import Router from 'vue-router'// Step 1 Vue.use(Router)export default new Router({
  routes: [
    {
      path: '/',
      redirect: "/login"]})},Copy the code
// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'New Vue({// Step 2 Router, render: h => h(App)}).$mount('#app')

Copy the code

The above is the basic configuration of vue-router. From the configuration, we can see that the application process of vue-Router is divided into two steps:

  • Vue.use(Router)Vue useRouterThe plug-in
  • theRouterThe real column is added toVue.$options

Plug-in implementation

Vue-router as a plug-in, first of all we need to achieve the development of the plug-in. Vue.js plug-ins should expose an install method. The first argument to this method is the Vue constructor, and the second argument is an optional option object:

let _Vue;
class VueRouter {
    constructor(options) {
       // ... 
    }
}

VueRouter.install = function(Vue) {// Avoid duplicate registrationif (VueRouter.installed && _Vue === Vue) return
    VueRouter.installed = true
    _Vue = Vue

    Vue.mixin({
        beforeCreate() {
            if (this.$options.router) {
                /**
                 *  this.$options.router === new Vue({router,}) * */ / Mount the router instance to Vue prototype so that all pages can access Vue. Prototype.$router = this.$options.router
                this.$options.router.init()}}})} vue.use (router) is called 'router.install (Vue)'Copy the code

The realization of the VueRouter

As you can see above, after vue.use (Router), our init() method is called. So now we need to implement our init().

init() {// bind the listener event this.bindevents () // create the route map this.createrouterMap (this.$options// Router-link RouterLView implements this.initCompontents()}Copy the code

Init () can be implemented in three steps:

  • Listening to thehashchangeEvent to maintain the modified value of the path
  • Route filerouter.routesObject to extract the corresponding component during route rendering
  • Implementation of routing components

Listen for an event

Routes are triggered by events, so by default bind events in load, hashchange, and maintain the current path when events are triggered

Class VueRouter {constructor(options) {// Route file configuration this.$optionsThis.routermap = new map () // path Maintains the path key of the current page, which is initialized by default'/'
    this.app = new Vue({
      data() {
        return {
          path: '/'}}})}init() {// Bind the event this.bindevents () // create the route map this.createrouterMap (this.$optionsThis.initcompontents ()}bindEvents() {// bind hashchange againsthashmodel'/#/xxx'
    window.addEventListener('hashchange', this.onhashchange) // Page initial window.adDeventListener ('load', enclosing onHashChange)} onHashChange (e) {/ / get the path of the modified values The path of the current path. This app. Path = window. The location. The hash. Slice (1) | |'/'}}Copy the code

Route map

We store all the information in the routing configuration file by maintaining the this.routerMap object

    // router.js
    export default new Router({
          routes: [
            {
              path: '/',
              name: 'home',
              component: Home,
            },
            {
              path: '/ui',
              name: 'ui', component: UI, }, ], }); Router.js createRouterMap(options) {// Maintain router.js configuration /** this.routerMap = [['/', {
                  path: '/',
                  name: 'home',
                  component: Home,
            },],
            [ '/ui', {
                  path: '/ui',
                  name: 'ui',
                  component: UI,
            },],
        ]*/
        
        options.routes.forEach(router => {
          this.routerMap.set(router.path, router)
        });
    }
Copy the code

Global component implementation

In vue-Router, there are two global components, router-Link and router-view. The effect of router-link is to jump through an A tag, and router-View is to render the corresponding page of the route.

 initCompontents<router-link> // <router-link to="/ui"</router-link> Vue.component('router-link', {props: {// The path to the jump passed by the component through props to: {typeRender (_h) {// _h is Vue createElement method // <a href ='#/ui'> Go to UI </a>return _h('a', { attrs: { 'href': The '#' + this.to } },[this.$slots.default])
        
      }
    })
    // 实现 <router-view> 
    Vue.component('router-view', { render: Const Comp = this.routerMap.get(this.app.path).component. (_h) => {// Component that gets jump path from route mapping object // Router-view tag placeholder to render when there is a componentreturn _h(Comp)
      }
    })
  }
Copy the code

So far, our simplified version of routing has been implemented, in the process, we are familiar with Vue plug-in development, component creation and event handling. Learning more about our Vue-Router, we can not only use it, but also write it. We all make progress together.

Dear friends, your likes are my support and encouragement. If they are helpful to you, you can leave your likes to support and encourage me. Thank you. I wish you all a happy and prosperous New Year.