preface

Key points:

  • Routing principle
  • The Hash and History
  • To implement the routing

The working principle of a VUE route

The differences between front-end routes and back-end routes:

Back-end route: Enter URL > request sent to the server > path of the server to resolve the request > take the corresponding page > Return to the front-end route: enter URL > JS resolve address > find the corresponding page > Execute the generated JS page > See the page

Vue-router workflow

Use of Hash and history

hash:

  • The hash is the content of the hash
  • You can get it from location.hash
  • You can listen for hash changes through onHashchange
  • You can add the path after the # sign without asking the server

history:

  • History is the normal path
  • location.pathname
  • You can use onPopState to listen for history changes

3. Basic knowledge of Vue plug-in

Vue-router, vuex, and Element-UI are plug-ins

Basic points of plug-in:

  • Vue.use to use a plug-in and execute the install method
  • Vue.mixin blends custom operations into the global Vue
  • You can call this.$options to get the new Vue parameters

Example:

The following is executed in main.js

1, initial vue.use ()

Vue.use({
console.log('use') // Prints use
})
Copy the code

2. Install properties

let a = function() {
  console.log(a)
}
// let a ={}
a.install=function(){
  console.log('install')
}
Vue.use(a) // Install will be printed instead of a.
// If you give him a method, he executes the method,
// But whatever you give him, just give him an install attribute and he will execute install.
Copy the code

3, Vue. Mixin ()

let a = function() {
  console.log(a)
}
// let a ={}
a.install=function(vue){
   // vue. mixin global mixin custom operations. The above vue is passed in as a parameter, not the vue in import vue from 'vue'
   vue.mixin({
    data () {
      return {
        c:123456 // In other pages this.c}},methods: {globalMethods(){
        console.log('I'm a global method') // In other pages this.globalmethods ()}},created() {
      console.log(this)
    }
  })
}
Vue.use(a) 
Copy the code

Vue utility classes: defineReactive, extend, mergeOptions, WARN

let obj = {
  key:'KEY'
}
setTimeout(function () {
  obj.key='KEY2' {{this.obj1.key}}
},3000)

let a = function() {
  console.log(a)
}
// let a ={}
a.install=function(vue){
  console.log(vue.util) // VUE utility classes: defineReactive, extend, mergeOptions, WARN
  vue.util.defineReactive(obj,'key')  / / to monitor. The source code uses Object.defineProperty()
  vue.mixin({
    beforeCreate(){
      this.obj1=obj // On other pages {{this.obj1.key}}, the value is key.}})}Copy the code

Vue.extend () differs from vue.util.extend() :

vue.extend() // Unit tests
const home = Vue.extend(home)
// Create a new constructor for this component, that is, this for the component
const vm = new home().$mount()
vue.util.extend() // Shallow copy object
Copy the code

Iv. Vue – Router

The following is a basic vue-Router that can only be switched between pages. This article is for familiarizing yourself with the source code, not for practical purposes. Create a folder named myRouter under SRC and create an index.js file. In index.js of the original router folder, change the path imported to the router to import VueRouter from ‘.. /myrouter’

Edit index.js in myRouter folder

// Record the history object
class HistoryRoute{
    constructor(){
        // The path to listen on
        this.current=null; }}/ / vuerouter itself
class vueRouter{
    constructor(options){
        this.mode=options.mode||'hash'; // Configure mode
        this.routes=options.routes||[]; // routes Routing table
        this.routesMap=this.createMap(this.routes); // Call createMap with routes
        this.history=new HistoryRoute;// instantiate history
        this.init(); / / initialization
    }
    init(){
        if(this.mode=='hash') {// Check whether it is hash mode
            location.hash?' ':location.hash='/'; // automatically add #. Returns an empty string if there is a hash. Otherwise return /
            window.addEventListener('load'.() = >{ // The listening page is loaded
                this.history.current=location.hash.slice(1); // Get the hash value, remove the #. The current path assigned to the instantiated history.
            })
            window.addEventListener('hashchange'.() = >{ // Listen for hash changes
                this.history.current=location.hash.slice(1); }}})// The path corresponds to the component. Compose a new object. For example, {'/':Home} is a mapping.
    createMap(routes){
        return routes.reduce((memo,current) = >{ // current indicates the routes table
            memo[current.path]=current.component;
            return memo
        },{})
    }
}

vueRouter.install=function(Vue){
    // Write a plug-in to check whether the plug-in is registered
    if(vueRouter.install.installed)return
    vueRouter.install.installed=true;
    // Add operations to vue
    Vue.mixin({
        beforeCreate(){
            if(this.$options&&this.$options.router){ // The router option is available in the app. vue file
                this._root=this; // This refers to the current Vue instance, caching itself.
                this._router=this.$options.router; // Mount the router passed in from the options.
                Vue.util.defineReactive(this.'current'.this._router.history); // Listen for this.current and pass a third argument. Equivalent to children.
            }else{
                this._root=this.$parent._root; // If not, go up one level until app. vue new vue ({router}) is found.
            }

            // This.$router is read-only
            Object.defineProperty(this."$router", {//this refers to the current component instance
                get(){ 
                    return this._root._router; // Return to the mounted router}})}})// Define the component
    Vue.component('router-view', {render(h){
           let current=this._self._root._router.history.current;// Get the current stored in the router instance
           let routerMap=this._self._root._router.routesMap;// Get the routesMap currently stored in the Router instance
           return h(routerMap[current]); // Get the routerMap and call h. Render the routerMap mapping. Put it in the router-View component.}})}/ / vuerouter exposure
export default vueRouter;
Copy the code

conclusion

On the road ahead we walk together.


Welcome to pay attention to my public account “front-end history robbery Road”

Reply keyword e-books, you can get nearly 12 front-end popular e-books.

Reply keywords little Red Book 4th edition, you can get the latest “JavaScript advanced Programming” (4th edition) ebook.

You can also add me to wechat. I have wooed many IT bigwigs and created a technical exchange and article sharing group. Welcome to join.

  • Author: Vam’s Golden Bean Road

  • Main area: front-end development

  • My wechat account is Maomin9761

  • Wechat public number: the front end of the road through robbery