1. Vue Router is an official route manager for vue. js (opens New Window). Its deep integration with vue.js core makes building single-page applications a breeze. The features included are:

    • Nested routing/view chart

    • Modular, component-based routing configuration

    • Route parameters, queries, and wildcards

    • View transition effect based on vue. js transition system

    • Fine-grained navigation control

    • Links with automatically activated CSS classes

    • HTML5 historical mode or Hash mode is automatically degraded in IE9

    • Custom scroll bar behavior

      I believe that you have written the VUE project, the vue-router routing plug-in is not unfamiliar, the specific use can be click on the following vue-router official documentation for detailed learning

      The official documentation

      Making the address

  2. Vue-router is one of the most frequently asked questions in interviews. What is the implementation principle behind vue-Router? what? The final answer is basically according to the URL bar changes, dynamic rendering corresponding components, can be specific how to achieve it, this is also a direction I recently learned, this simple implementation of a basic vue-Router plug-in

  3. First of all, we know that vue-Router has two modes, which are history mode and Hash mode respectively. The reason why SPA single page changes but the page does not refresh lies in these two modes. Today we implement hash mode, and we will implement history in the future

    • The installation

      vue add vue-router
      Copy the code

      We can directly use the vUE official scaffolding command, installation, installation will change the code, remember to save oh

    • The folder is normally generated, and the files mainly used for vue-router are

      Where index.js is the router folder and the router configuration item generated by us

      And main.js is the entry for packaging

      App.vue is the application of routing, familiar taste, familiar recipe…

      Now that the environment is ready, let’s implement the plugin. In index.js, you can also see the commented out my-router.js.

    • When we configure roputer, according to the mechanism of the Vue plug-in, when using the vue.use (‘ XXX ‘) method, the plug-in’s install method is called and the root instance of Vue is passed in.

      Let’s start with the basic VueRouter class

      // Vue -router class VueRouter{constructor(options){// Save the configuration item and call this.options = for the Vue mounted in mian.js VueRouter. Install =(_Vue)=>{Vue = _Vue} export default VueRouterCopy the code
    • The basic writing method should be solved first, now the page should report an error, we used in app.vue, there is no registration definition, so let’s register the two components normally first

      // <router-link to="/">Home</router-link> </router-link> props: { to: { type: String, required: $slot. default render(h) {return h('a', { attrs: { href: '#' + this.to, }, }, this.$slots.default ) }, } }Copy the code
    • Now, routing placeholders, how does it render other components? Render (‘ component ‘); render(‘ component ‘); render(‘ component ‘); Where do you get components?

      //<router-view> function createRouterView(){return {render(h){ {component */ h(null)}}} {component */ h(null)}}Copy the code
    • We can get the routing table from the new VueRouter instance, starting with question 1. We know that the location of the Windo object can get the hash value directly. In the instance, we can get the URL of each change through the event.

    • Let’s start with the VueRouter class

      Class VueRouter{constructor(options){this.options = options // Get the initial value # this Window. The location. The hash. Slice (1) | | '/' / / hash event monitoring, and each assignment again the current window. The addEventListener (' hashchange '() = > {this. Current =  window.location.hash.slice(1) }) } }Copy the code
    • $options = router = router = router = router = router = router = router = router = router = router = router = router = router Methods in series, when did you do it? The answer is mixins, which we can use to blend our instance of VueRouter into the vUe-initialized hook function

      VueRouter. Install = function(_Vue){// Global definition of Vue Vue = _Vue Vue. Mixin ({// Use beforeCreate, is the first initialization of the hook mixed with beforeCreate(){ If (this.$options.router){// If (this.$options.router){// If (this.$options.router){// If (this.$options.router){// If (this.$options.router){// If (this.$options.router){// If (this this.$options.router } } }) }Copy the code
    • And then we can finish

      //<router-view> function createRouterView(){ return { render(h){ const { current , {routes}} = this.$router // Add path to component const currentComponent = routes. Find (route => route.path === current).component h(currentComponent) } } }Copy the code
    • Nice, what’s up? Just click… W:? Emmmmm, how can the URL change, do not render the corresponding component? Isn’t Vue responsive, huh? In Vue, data changes correspond to view updates, but our current is not responsive data,Vue does not perform the corresponding update function, so change current to responsive data. How do I do that? You can’t use Object.defineProperty() anymore, that’s too much trouble. Var util. DefineReactive (target,key,val), observe bind to initState (more on that later). So let’s start working on the code

      Let Vue class VueRouter{constructor(options){this.options = options this.current  = window.location.hash.slice(1) || '/' window.addEventListener('hashchange',()=>{ this.current = Window. The location. The hash. Slice (1)}) / / current into a responsive data Vue. Util. DefineReactive (this, 'current', enclosing the current)}}Copy the code
    • The most basic vue-Router is implemented

  4. This is the whole set of process combing

  5. Conclusion:

    • Vue plug-in mechanism, need to implement install method,install the first parameter for Vue instance, need to save globally

    • The render function in the component is used to render the component to ensure proper compilation of the code

    • In VueRouter, save url and options as its own instance attributes, get the VueRouter instance from main.js, and get the router.js configuration, mix the VueRouter instance globally through vuue Ue root instance in the prototype for invocation in individual components

    • Use vue.util.definereactive () to change the HASH value of the URL into responsive data, so that when the URL changes, the corresponding update function is triggered to render again

This series is a record of my daily study, and there are still many shortcomings and mistakes in it. I hope that the master with good technology can point out my mistakes and shortcomings. I am very grateful. I will continue to update various series to commemorate the first time I wrote an article… I hope years from now, I can still remember my passion for code and technology… If there is infringement, please contact me… thank you