SoFunction
Updated on 2025-04-06

vue-router source code implementation a simple vue-router

Preface

Through the previous article, we know two implementation methods of front-end reason, Hash routing and History routing, and use them to implement a front-end routing respectively.

Next, we combine Vue with Hash routing to implement a very simple vue-router.

Begin to implement

Imagine how to use it if you implement a vue-router? Refer to the official use of vue-router to see the use of html:

<div >
 <p>
  <router-link to="#/">home</router-link>
  <router-link to="#/book">book</router-link>
  <router-link to="#/movie">movie</router-link>
 </p>
 <router-view></router-view>
</div>

Here we will implement two components: router-link and router-view. Let's look at js:

const Home = { template: '<div>home</div>' };
const Book = { template: '<div>book</div>' };
const Movie = { template: '<div>movie</div>' };

const routes = [
 { path: '/', component: Home },
 { path: '/book', component: Book },
 { path: '/movie', component: Movie }
];

const router = new VueRouter(Vue, {
 routes
});

new Vue({
 el: '#app'
});

Here we will define our own components Home, Book and Movie, and we will have their own corresponding routes. The VueRouter we implemented is somewhat different from the official one. When VueRouter is new, Vue is passed in as a parameter, rather than injecting and mounting it to the root instance.

Next is the implementation of VueRouter.

VueRouter

How to implement VueRouter? First, provide the implementation ideas:

  1. Bind hashchange events to implement front-end routing;
  2. Map the incoming routes and components in a route, and switch which route to find the corresponding component display;
  3. It is necessary to have a new Vue instance and perform responsive communication. When the route changes, the router-view will respond to updates;
  4. Register the router-link and router-view components.

Create a VueRouter first:

class VueRouter {
 constructor (Vue, options) {
  this.$options = options;
 }
}

Binding events

Add a binding event method to VueRouter, which will trigger once the route changes.onHashChange method.

constructor (Vue, options) {
 ();
}

// Binding eventsinit () {
 ('load', (this), false);
 ('hashchange', (this), false);
}

Routing Map Table

Set the incoming options into a routing mapping table to facilitate the search of corresponding components through routes.

constructor (Vue, options) {
 this.$options = options;
  = {};
 (this.$options);
}

//Route Mapping TablecreateRouteMap (options) {
 (item =&gt; {
  [] = ;
 });
}

Among options, the relationship between routes and components:

const routes = [
 { path: '/', component: Home },
 { path: '/book', component: Book },
 { path: '/movie', component: Movie }
];

The generated routing map table:

 = {
 '/': Home,
 '/book': Book,
 '/movie': Movie
};

response

We need to new a new Vue instance and store the current route current in its data. When the current is modified, the router-view will update the view itself.

constructor (Vue, options) {
  = new Vue({
  data: {
   current: '#/'
  }
 });
}

// Get the current hash stringgetHash () {
 return (1) || '/';
}


// Set the current pathonHashChange () {
  = ();
}

As long as it is router-view Used in, Once it is updated, it will be updated.

Register components

router-link It's actually a <a> tag, clicking it can trigger ithashchangerouter-view A render method will be implemented to take out the corresponding components of the current route and render.

constructor (Vue, options) {
 (Vue);
}

// Register componentsinitComponent (Vue) {
 ('router-link', {
  props: {
   to: String
  },
  template: '&lt;a :href="to" rel="external nofollow" rel="external nofollow" &gt;&lt;slot&gt;&lt;/slot&gt;&lt;/a&gt;'
 });

 const _this = this;
 ('router-view', {
  render (h) {
   var component = _this.routeMap[_this.];
   return h(component);
  }
 });
}

Complete code

At this point, a simple vue-router came out, and the whole code was like this:

class VueRouter {
 constructor (Vue, options) {
  this.$options = options;
   = {};
   = new Vue({
   data: {
    current: '#/'
   }
  });

  ();
  (this.$options);
  (Vue);
 }

 // Binding events init () {
  ('load', (this), false);
  ('hashchange', (this), false);
 }

 //Route Mapping Table createRouteMap (options) {
  (item =&gt; {
   [] = ;
  });
 }

 // Register components initComponent (Vue) {
  ('router-link', {
   props: {
    to: String
   },
   template: '&lt;a :href="to" rel="external nofollow" rel="external nofollow" &gt;&lt;slot&gt;&lt;/slot&gt;&lt;/a&gt;'
  });

  const _this = this;
  ('router-view', {
   render (h) {
    var component = _this.routeMap[_this.];
    return h(component);
   }
  });
 }

 // Get the current hash string getHash () {
  return (1) || '/';
 }

 // Set the current path onHashChange () {
   = ();
 }
}

at last

Combining Vue with Hash routing, listening for hashchange events, and then through Vue's response mechanism and components, the above implementation of a vue-router is achieved.

All source code referenceshere

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.