Vue-router Fundamentals Review

Using the step

  1. Create the routeR object routeR /index.js
Import Vue from 'Vue' import VueRouter from 'vuue-router' // Import Index from '.. Use (VueRouter) // const routes = [{path: '/', name: 'Index', Component: Index }, ] // 2. Const router = new VueRouter({routes}) export default RouterCopy the code
  1. Register the router object main.js
import Vue from 'vue' import App from './App.vue' import router from './router' Vue.config.productionTip = false new Vue({ // 3. Router, render: h => h(App)}).$mount('# App ')Copy the code
  1. Create route component station app.vue
    <router-view/>
Copy the code
  1. Create a connection
    <router-link to="/">Index</router-link> |
    <router-link to="/blog">Blog</router-link> |
Copy the code

Dynamic route parameter transmission

  1. Obtain $route.params.id from the current routing rule
Const routes = [{// Path: "/detail/:id", name: "detail ", component: Detail}] // The Detail component accepts the route parameter //$route.params.idCopy the code
  • Idea: Get parameters by routing rules, rely heavily on routes, and pass parameters when using components
  1. Obtain this parameter by enabling props
Const routes = [{// Path: "/detail/:id", name: "detail ", component: Detail, // enable the props to pass the URL parameter to the component // Accept the URL parameter props:true}] // The Detail component to accept the routing parameter export default {props:["id"], Template :' Detail ID: {{ID}}</div>}Copy the code

Embedded routines by

  • The Index and Details components nest layout components
{
    path: '/',
    component: Layout,
    children: [
      {
        name: 'index',
        path: '',
        component: Index
      },
      {
        name: 'detail',
        path: 'detail/:id',
        props: true,
        component: () => import('@/views/Detail.vue')
      }
    ]
  }
Copy the code

Programmatic navigation

Router.push ('/login') // Named route router.push({name: 'user', params: {id: Router.replace () router.go()Copy the code

Difference between Hash mode and History mode

  1. Both modes are the implementation of client routing. When the path changes, it will not send requests to the server. Js is used to monitor the path changes and render different contents according to different addresses. If you need server-side content, send an Ajax request to get it.
  • The difference of expression form
    • Hash pattern
      • Music.163.com/#/listPage?…
    • The History mode
      • Music.163.com/listPage/31…
  • Difference in principle
    • Hash pattern
      • The Vue Router uses hash mode by default, using hash to simulate a complete URL and listening for path changes with onhashchange
    • The History mode
      • Based on the History of API
      history.pushState() 
      history.replaceState() 
      history.go()
      Copy the code
  • Enable History mode
const router = new VueRouter({
 mode: 'history',
 routes
})
Copy the code
  • Use of HTML5 History mode
  1. History requires server support
  2. In a single-page application, if the server does not have an address such as www.testurl.com/login, the page cannot be found
  3. The server should return single-page application index.html for all but static resources

Vue Router simulation implementation

  • Pre-knowledge: plugins, slot slots, mixins, render functions, runtime, and full Vue

Hash pattern

  • The content after # in the URL is the path address
  • Listen for the hashChange event
  • Find the corresponding component based on the current routing address and re-render

The History mode

  • Change the address bar with the history.pushstate () method
  • The popState event can be used to listen for browser address changes. The popState event handler can be used to record the changed address. Note that pushState or replaceState does not trigger this event. Or when the back and forward methods of history are called
  • Find the corresponding component based on the current routing address and re-render

Review the core code

The class diagram

  • The VueRouter property has the Options Data routeMap property
  1. Options records objects passed into the constructor
  2. RouteMap records the relationship between routing addresses and components
  3. The data property has a current record of the current routing address. Data is a responsive object, because when the routing address changes, the corresponding component also needs to update accordingly

Create the VueRouter plug-in

Let _Vue = null export default class VueRouter {static install (Vue) {// 1 Check whether the current plug-in is installed If (VueRouter. Install. Installed) {return} VueRouter. The installed = true / / 2 records the constructor of the vue to global variables _Vue = vue / / 3 Mixin ({beforeCreate () {// Determine whether the router object has been mounted on the Vue instance Prototype.$router = this.$options.router _Vue.prototype.$router.init() } } }) } }Copy the code

Implement the constructor of the VueRouter class

RouteMap = {} this.data = _vue.Observable ({// The current default path  current: "/" }) }Copy the code

Implement the VueRouter class createRouteMap

createRouteMap(){ // routes => [{ name: '', path: '', component: }] // Loop through the routing rules, parse them into key-value pairs, Stored in the routeMap enclosing options. Routes. ForEach ((route) = > {enclosing routeMap [route. The path] = route.com ponent})}Copy the code

Implement VueRouter class – register events

 initEvents () {
     window.addEventListener("popstate", ()=>{
       this.data.current = window.location.pathname
     })
 }
Copy the code

Implement the VueRouter class – router-link and router-view components

InitComponents (Vue) {Vue.component('router-link', {props: {to: String}, // Need vue.js with compiler version // template: "< a href = '\ +" # \' to '> < slot > < / slot > < / a > "/ / use the runtime version of the Vue. Js render (h) (' a', {{return h attrs: { href:'#' + this.to }, on: { click: this.clickHandler } }, [this.$slots.default]) }, methods: { clickHandler (e) { history.pushState({}, "", this.to) this.$router.data.current = this.to e.preventDefault() } } }) const self = this Vue.component('router-view', Render (h) {const Component = self.routemap [self.data.current] return h(component)}}Copy the code

A build of Vue

  • Runtime version: Does not support template templates and is compiled ahead of time when packaging is required

  • Full version: contains the runtime and compiler, which is about 10K larger than the runtime version, and converts the template into the render function when the program runs

  • Note:

    • Vue-cli-created projects use the runtime version vue.js by default
    • If you want to switch to vue.js with the compiler version, you need to change itVue – cli configuration
      • Create a vue.config.js file in the project root directory and add runtimeCompiler
      module.exports = {
         runtimeCompiler: true
      }
      Copy the code

Implement VueRouter – init()

Init (){this.createroutemap () this.initComponents(_Vue) this.initEvents()} // Init () is called in the install() method of the plugin to initialize if Prototype.$router = this.$options.router ()}Copy the code