This is the fifth day of my participation in the August Wen Challenge.More challenges in August”

introduce

From Baidu Encyclopedia: A single Page Web application (SPA) is a single Web page application that loads a single HTML page and dynamically updates the page as the user interacts with the application. In fact, the difference from the previous application without separating the front and back ends is that the page will not be refreshed when switching pages, which will greatly improve the user experience. Currently, there are two commonly used modes in the browser, namely Hash and History routing

Single-page apps and multi-page apps

Single page

  • None Refresh Updated the page to improve user experience
  • Seo optimization is poor becauseseoYou can recognize content in HTML, not content in JS, but pages are rendered in JS
  • The loading of the first screen will be slower, because the page will be displayed only after the corresponding HTML and JS are loaded for the first time. Some optimization methods can be adopted to solve such problems as splitting resource server rendering

Multiple page

  • The first screen loads faster and the server returns one when a page is visitedhtmlIt will then be shown directly that the entire process is a single HTML request
  • Seo optimization results will be better
  • The page switching effect is not as good as the single page application experience

The differences between the two routes

Hash

  • The principles behind the Hash pattern depend onhashChangeEvent to listen for updates
  • The hash route displays a # in the URL, which doesn’t look pretty
  • We refresh the route with carriage returnhashWill be loaded into the address bar corresponding to the page, andhistoryRouting usually reports404The reason is that the history refresh is a network request and an error will be reported if the back end is not prepared
  • Hash routing supports browsers of earlier versions and compatibility ratiohistoryPattern strong, history isHTML5The new API
  • Hash parameter passing is based onurlThe length of the parameter is limited

History

  • The history route leverages the browser history stack, which was previously availableBack, forward, goMethod, which was added laterpushStateandrepleaseStatemethods
  • Currently these two methods are compatible and require specific browser support. There is the ability to modify the browser history. Even if you change the current URL, your browser will not immediately send a request to the backend

instructions

The React and Vue routing modes are based on the above two implementations. Today we use vue-router as an example to implement a basic version of vue-router routing

start

We need to create a basic shelf using the official vUE generation tool, then create two base pages to show the content of the switch, as before there will be a lot of comments in the code

Create home.vue and list.vue

//home.vue
<template>
  <div>
  home
  </div>
</template>
​
<script>
​
export default{}; </script><style scoped></style>Copy the code
//list.vue
<template>
  <div>
  list
  </div>
</template>
<script>
export default{};</script>
<style scoped></style>Copy the code

Mount the router in the vue root directory main.js

//main.jsimport Vue from 'vue'
import App from './App.vue'
import router from './lrouter'// This is the route we want to implement
​
Vue.config.productionTip = falsenew Vue({
  router,
  render: h= > h(App),
}).$mount('#app')
​
Copy the code

Create index.js under lRouter to write route list

//index.js
import Vue from 'vue'
import vueRouter from './lvue-router'
import Home from '.. /views/home.vue'
import List from '.. /views/list.vue'// Execute the internal install method
Vue.use(vueRouter)
​
const routes = [{
    path: "/".name: "Home".component: Home
}, {
    path: "/list".name: "List".component: List
}]
​
export default new vueRouter({ routes })
Copy the code

We then create lvue-router.js in the current directory to write our main logic, and then write all the logic that belongs to the current page

//lvue-router.jslet Vue = null// The install method is called by the outer vue. use
VueRouter.install = function (_vue) {
    // Get Vue to be used later in class VueRouter
    Vue = _vue
    //1. Mount the instance to ensure that this calls $router globally
    // Mix with global mixins
    Vue.mixin({
        beforeCreate() {
            if (this.$options.router) {
                // the first instantiation is called once in main.js
                Vue.prototype.$router = this.$options.router
            }
        }
    })
}
​
Copy the code

1. Register the global component router-link in install

​
VueRouter.install = function (_vue) {
    //2. Register global components
    Vue.component('router-link', {
        props: {
            to: {
                type: String.required: true}},// Execute the render function
        render(h) {
            return h('a', { attrs: { href: ` #The ${this.to}`}},this.$slots.default)
        }
    })
}
​
Copy the code

2. Register the global component router-view in install

Vue.component('router-view', {
  render(h) {
    let Component = null
    // Execute the current method to update the page when this.$router.current changes
    let res = this.$router.$options.routes.find(v= > v.path === this.$router.current)
    if (res.component) {
      Component = res.component
    }
    return h(Component)
  }
})
Copy the code

Create VueRouter class

class VueRouter {
    constructor(options) {
        this.$options = options
        let initial = window.location.hash.slice(1) // Take the argument after #
        Vue.util.defineReactive(this.'current', initial) // Change the current variable to reactive
        window.addEventListener('hashchange'.this.hashChange.bind(this)) // Register the hashChange method to listen for changes
    }
    hashChange() {
        this.current = window.location.hash.slice(1) // Take the argument after #}}export default VueRouter
Copy the code

Effect of the page

The end of the

Vue-router basic functions to achieve here almost, what questions can be discussed in the comment area ☕️