The basic use

  • The directory structure:

  • The sample code:
// Sample code: SRC /main.js
import Vue from 'vue'
import App from './App.vue'
import router from "./router";

new Vue({
  // Mount the router to the vue instance
  // Make the entire application routable
  router,
  // The main entry renders the App component and provides route jump links in the App component template
  render: h= > h(App),
}).$mount('#app')

Copy the code
// Sample code: SRC/app.vue
<template id="app">
  <div>
    <h1>I'm the home page of the App component</h1>

    <! -- Use the router-link component to navigate.
    <! -- Specifies the link by passing in the 'to' attribute.
    <! -- Router-link is rendered as a '<a>' tag by default.
    <router-link to="/home">Go to Home</router-link>
    <br />
    <router-link to="/about">Go to About</router-link>

    <! -- Routing matching components will be rendered here -->
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  template: '#app'
}
</script>

Copy the code
// Example code: SRC /router/index.js
import Vue from "vue";
import VueRouter from "vue-router";
import Home from ".. /components/Home.vue";
import About from ".. /components/About.vue";

Vue. Use (VueRouter) to install the plugin if you are programming with the modularity mechanism and import Vue and VueRouter

Use Vue. Use (plug-in) to install the plug-in
Vue.use(VueRouter);

// 2. Configure a route mapping group
const routes = [
    { path: '/home'.component: Home },
    { path: '/about'.component: About },
]

// 3. Generate a route instance
const router = new VueRouter({
    routes
})

// 4. Export the route instance for mounting to the VUE instance
export default router;
Copy the code
// Sample code: SRC /components/ home.vue
<template id="home">
  <div>
    <h1>I am a home page</h1>
  </div>
</template>
<script>
export default {
  template: '#home'
}
</script>
Copy the code
  • The results show:

Two modes of routing

Vue-router provides two ways to implement front-end routing :Hash mode and History mode. The mode parameter can be used to determine which mode to use

/ / sample:
const router = new VueRouter({
    //mode specifies the history mode; If this parameter is not specified, the route uses hash mode by default
    mode: 'history'.routes: [...]. })Copy the code

1. The Hash pattern

Vue-router uses Hash mode by default. Use a URL hash to simulate a complete URL. The browser will not reload the URL if it changes. Hash(that is, #) is the anchor point of the URL and represents a location in the web page. Simply change the following part of the # and the browser will scroll through the location without reloading the page. It is just a guide to the browser and has no effect on the server at all! It is not included in the HTTP request and therefore does not reload the page. And when the hash changes, the URL is logged by the browser, so you can use the browser’s back.

To summarize: Hash mode is a way to implement browser-rendered components by changing the value after #.

2. The History mode

This pattern takes advantage of the new HTML5 History pushState() and replaceState() methods. In addition to the previous back, Forward, and Go methods, the two new methods can be used to add and replace browser history. Using History mode, the URL is modified through History, but it does not immediately send a request to the back end.

Note: Although History mode can discard ugly # and move forward or backward normally, refreshing F5 will result in a 404! “However, to play this mode well, you need to support the background configuration,” the official document states. Because our application is a single client application, if the background is not properly configured, 404 will be returned when the user accesses it directly. So, you add a candidate resource on the server that covers all cases; If the URL does not match any static resources, the same index.html page should be returned.

To summarize :History mode is a way to modify the browser's History through pushState() without asking the back end to render it. However, it is recommended to use the history mode for the actual project.

Default route path

By default, when we go to the front page of the site, we want to render the content of the front page

// Example: Default route configuration
const routes = [
    // Configure the default route to redirect directly to /Home component when accessing the root path /
    { path: '/'.redirect: '/Home' },
    { path: '/home'.component: Home },
]
Copy the code

router-link

  1. to: Specifies the jump path
  2. tag:<router-link>The default is render to<a>Tag component, which can be specified using tag<router-link>Render into what components.
<! -- Example: -->
<! -- The default home page display is a tag -->
<router-link to="/home">Home page</router-link>
<! -- tag specifies the home page to appear on the button tag -->
<router-link to="/home" tag="button">Home page</router-link>
Copy the code
  1. replace: Does not leave a history and cannot go back to the previous step using the browser’s back button
<router-link to="/home" tag="button" replace>Home page</router-link>
Copy the code
  1. active-class: By default, when you click router-link, the active class attribute isrouter-link-active, you can style the active tag based on the active class, butrouter-link-activeIt’s too long to useactive-classArtificially rename the labelbriefThe active class property of But when there are many tags each needs to be specifiedactive-classIt’s tedious. We can do it in
<router-link to="/home" tag="button" replace
active-class="active" >Home page</router-link>
Copy the code
/ / sample:
const router = new VueRouter({
    // mode No write The default value is hash
    mode: 'history',
    routes,
    // linkActiveClass specifies that the active class attribute of all router-links should be named active
    linkActiveClass: 'active'
})

Copy the code

The history of h5

Code controls the jump route

  • this.$router: Each route instance has one$routerRepresents the entire Router instance object.
<template id="app">
  <div>
    <h1>I'm the home page of the App component</h1>
    <! -- <router-link to="/home">Go to Home</router-link> <router-link to="/about">Go to About</router-link> -->

    <div @click="clickHome">Home page</div>
    <div @click="clickAbout">about</div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  template: '#app'.methods: {
    clickHome () {
        // Each group price has a '$router' attribute
        // The push method provides a routing path
        // The route set by the push method can be switched forward or backward by using the browser back button. If no switch is required, the route can be passed
        // this.$router.replace('/home')
      this.$router.push('/home')
    },
    clickAbout () {
        // this.$router.replace('/about')
      this.$router.push('/about')}}}</script>
Copy the code

Dynamic routing

// Route attributes:
1.$route.path: string; The path of the current route is always resolved to an absolute path, for example"/foo/bar"
2.$route.params: object; A key/value object that contains dynamic fragments and fully matched fragments and is empty if there are no routing parameters3.$route.query: object; A key/value object representing a URL query parameter. For example, for path /foo? user=1$route.query.user ==1, is an empty object if there are no query parameters.4.$route. name: specifies the name of the current route, if any. It is recommended that each routing object be named for later programmatic navigation. But remember that the name must be unique!5.$route.hash: string; Hash value (with #) of the current route, or empty string if no hash value exists.6.$route.fullPath: string; The parsed URL contains the query parameters and the full path to the hash.7.$route. Matched:ArrayThe < RouteRecord > type; An array containing routing records for all nested path fragments of the current route. The routing record is a copy of the objects in the Routes configuration array (and in the Children array).8.$route.redirectedFrom: Specifies the name of the route from which the source is redirected, if anyCopy the code
// '$route.matched' : an array containing routing records.

// router/index.js
const routes = [
    {
        path: '/home'.component: Home,
        children: [{path: 'news'.component: HomeNews,
            }
        ]
    },
    { path: '/about'.component: About },
]

// HomeNews.vue
export default {
  template: '#news',
  activated () {
    // When HomeNews is active, this.$route.matched console outputs the following value
    // this.$route.matched: [
    // 0 subscript: {path: "/home"... },
    // 1 subscript: {path: "/home/news",... }
    // ]
    console.log(this.$route); }}Copy the code

1. Dynamic routes are used

<! -- App.vue -->
<template id="app">
  <div>
    <router-link to="/home">Home page</router-link>
    <! -- Use v-bind to bind the userId to the jump route. Also note the use of single quotes around '/user/', telling vi-bind /user/ that it is a string and not a variable. /user/xiaoming -->
    <router-link v-bind:to=" '/user/' + userId ">The user</router-link>
    <! -- Routing matching components will be rendered here -->
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  template: '#app',
  data () {
    return {
      userId: ' '}}}</script>
Copy the code
// router/index.js
const routes = [
    { path: '/home'.component: Home },
    // Jump from app. vue component router-link :to=" '/user/' + userId"
    // Dynamic path parameters start with a colon. UserId is the dynamic route that receives the xiaoming of /user/xiaoming passed by the user
    { path: '/user/:userId'.component: User },
]
Copy the code
// User.vue
export default {
  template: '#user'.computed: {
    userName () {
      // The user.vue component gets the value of the passed parameter through this.$route.params.userId
      return this.$route.params.userId
    }
  }
}
Copy the code

Responds to route parameter changes

Because the routing parameters are reusable to the component instance. For example, /user/foo and /user/bar reuse the user component when using routing parameters. The component’s lifecycle hook is no longer called. If you want to do some initialization when switching paths, you can use the following two solutions:

// Watch $route object inside component:
const User = {
 template: '... '.watch: {
   '$route' (to, from) {
     // Respond to routing changes...}}}// Approach 2: Use beforeRouteUpdate in version 2.2
const User = {
  template: '... ',
  beforeRouteUpdate (to, from, next) {
	// react to route changes...
	// don't forget to call next()}}Copy the code

Matching priority

  • A path can match multiple routes. In this case, the matching priorities are in the order of route definition: The one defined first has the highest priority.

Embedded routines by

  • Example: Nested messages and News components in the Home component
  • Display the nested child route in the parent route template, the parent route template to a child nested route exitrouter-view
// router/index.js
// Configure children nested routines with children
const routes = [
    {
        path: '/home'.component: Home,
        children: [{// The path of the nested child component does not need to be written with '/', which is added automatically when accessing /home/news
                path: 'news'.component: HomeNews,
            },
            {
                path: 'messages'.component: HomeMessages,
            }
        ]
    },
    { path: '/about'.component: About },
]
Copy the code
<! -- Homenews.vue -->
<template id="news">
  <div id="app">
    <h2>I'm the News component</h2>
  </div>
</template>
<script>
export default {
  template: '#news'
}
</script>
Copy the code
<! -- Home.vue component -->
<! -- Method 1: After the page renders the home component, the nested child component will not be displayed. We need to enter '/ home /news' in the address bar to access it.
<template id="home">
  <div>
    <h1>I am a home page</h1>
    <! Nested render exit of child route in parent route Home template -->
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  template: '#home'
}
</script>

<! -- Home.vue component -->
<! -- Option 2: In the home component, provide a jump link, through the jump link instead of manually enter in the address bar -->
<template id="home">
  <div>
    <h1>I am a home page</h1>
    <! Instead of manually typing in the address bar -->
    <router-link to="/home/news">news</router-link>
    <router-link to="/home/messages">The message</router-link>
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  template: '#home'
}
</script>
Copy the code

Routing and the cords

1. Params parameter transfer mode

  • After params passes the parameter, it will eventually appear in the address bar as well
  • this.$route.params***:$routeRepresents the currently active routing component,this.$route.paramsYou can get the parameters received by the current active route.
  • aThe path parameterUse a colon: The tag. When a route is matched, the parameter value is set tothis.$route.paramsCan be used within each component
model Matching path $route.params
/user/:username /user/evan { username: ‘evan’ }
/user/:username/post/:post_id /user/evan/post/123 { username: ‘evan’, post_id: ‘123’ }
/ / sample
{ path: '/user/:userId'.component: User} Access path: / User /xiaoming passesthis$route.params.userId Can obtain the value xiaomingCopy the code

2. Query Parameter transmission mode

  • In the project we can pass the parameter through params mentioned above. You can also use query to pass parameters. Here’s an example:<router-link to="/user? id=foo">foo</router-link>Vue-route automatically links? The following id=foo is encapsulated in this.
    r o u t e . q u e r y In the . At this time . In the component t h i s . The route in the query. Now, inside the component, this.
    The route. The query. The id value for the ‘foo’.
  • When the parameter is passed through query, the parameter also ends up in the address bar
  • In addition torouter-linkthetoProperties.queryYou can also pass parameters through programmatic navigation as described below
<! -- App.vue -->
<router-link to="/about">about</router-link>
<router-link :to="{ path: '/about' }">About 2</router-link>
<! -- Query to bind an object to the path jump and query to the object -->
<router-link
    :to="{ path: '/profile', query: {name: 'lisi',age: 18} }"
>archives</router-link>
Copy the code
// Profile.vue
<script>
export default {
  template: '

I am a profile component {{this.$route.query}}

'
, } </script> // router/index.js { path: '/profile'.component: Profile }, Copy the code

3. Route parameters do not pass router-link

  • throughthis.$router.push( String | Object )
      1. this.$router.push('/user/' + this.userId)
      1. this.$router.push({ path: '/profile', query: {sex: 'girl'} })
<! -- App.vue -->
<! -- Router-link routing is not allowed -->
<button @click="userClick">User 1</button>
<button @click="profileClick">File 1</button>
methods: {
    userClick () {
        this.$router.push('/user/' + this.userId)
    },
    profileClick () {
        this.$router.push({
        path: '/profile',
        query: {
            sex: 'girl'
        }
        })
    }
}
Copy the code
// Profile.vue<h1> I am the profile component {{this.$route.query }}</h1>

// User.vue
<h2>{{this.$route.params}}</h2>
Copy the code

Navigation guard

  • Navigation guard: controls the operation during route forwarding
  • Navigational parsing idea: When a navigation is triggered, the global front-guard is called in the order it was created. The guard is asynchronously parsed to execute, at this time navigation in all guardsresolveI was waiting until I finished. That is, the hook functions queue up in the pipe in order to navigate through the hook functionsnext()To execute the next hook function in the pipe. If all the hook functions in the queue are executed, the state of the navigation isconfirmed
  • Each guard method receives three arguments:
1.To: Route: indicates the destination Route to be entered2. from: Route: indicates the Route the current navigation is about to leave3. next: FunctionBe sure to call this method to resolve the hook. The execution depends on the call parameters of the next method. -next (): carries out the next hook in the pipe. If all hooks are executed, the navigation state is confirmed. - next(false): interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset tofromIndicates the IP address of the route. - next('/') or the next ({path: '/'}): jumps to a different address. The current navigation is interrupted and a new navigation is performed. You can pass any position object to next, and you can set things like replace:true, name:'home'And any options used in router-link's to prop or router.push. - next(error): (2.4. 0+) if the argument passed to next is oneErrorInstance, the navigation is terminated and the error is passed to the callback registered with router.onerror ().Copy the code
    // Detailed instructions for using the function and next()
    router.beforeEach((to, from, next) = > { 
	// To and FROM are actually routing objects, so the attributes of the routing object are available.
	// For example, I want to get the full path to is to.path. the child path of to is to.matched[0].
      next();// Do not omit next!!

	// Next () goes directly to the next hook.
	//next(false) interrupts current navigation
	//next('/path path ') or object next({path:'/path path '}) jumps to path routing address
	//next({path:'/shotcat',name:'shotCat',replace:true,query:{logoin:true}... } router-link to prop and router.push Replace :true is used to replace the current route address, which is used to modify the route after permission judgment.
    // Next (error) (2.4.0+)
    }).catch(() = >{
        // Jump to the failed page
        next({ path: '/error'.replace: true.query: { back: false}})})Router.onerror () router.onError() router.onError()
router.onError(callback= > { 
    console.log('Wrong! ', callback);
});

Copy the code

1. Global guard

  • Global guard: Is executed asynchronously. Each hop is executed sequentially.
Global front-guard: callback before route jump
router.beforeEach((to, from, next) = >{
    next()
}): 
The global parse guard (2.5.0+) is called after the beforeRouteEnter call.
router.beforeResolve

// 3. Global post-hook: callback after route jump Note: next() is not supported; I can only write it this way
router.afterEach((to, from) = > {});
Copy the code
  • Code sample:
router.beforeEach((to, from, next) = > {
    // Jump from from to to
    // document.title = to.meta.title;
    document.title = to.matched[0].meta.title;

    // From and to are both route objects
    // Next must be called
    next()  
})
Copy the code

2. Route exclusive guard

  • Route exclusive guard: Guard exclusive to the routing object
// 1. The route has only one hook function, which is configured in rutes and executed before redirecting the route
beforeEnter: (to, from, next) = > {
    next()
}

Copy the code
  • Code sample:
const router = new VueRouter({
  routes: [{path: '/foo'.component: Foo,
      beforeEnter: (to, from, next) = > {
        // ...}}}])Copy the code

3. Guards within components

  • Guards within components: Route navigation guard written inside the component
1.BeforeRouteEnter Before entering the route, the instance is not created and the ZHIS cannot be obtained2. beforeRouteUpdate (2.2) when routes are multiplexed with the same component3.BeforeRouteLeave Leaves the current route and can be used to save data, initialize data, turn off timers, and so onCopy the code
  • Code sample:
const Foo = {
  template: `... `,
  beforeRouteEnter (to, from, next) {
    // called before the corresponding route to render the component is confirmed
    / / no! Can!!!! Gets component instance 'this'. Because the component instance has not been created before the guard executes
  },
  beforeRouteUpdate (to, from, next) {
    // Called when the current route changes but the component is being reused
    // For example, for a path /foo/:id with dynamic parameters, when jumping between /foo/1 and /foo/2,
    // Since the same Foo component will be rendered, the component instance will be reused. And the hook will be called in that case.
    // Access component instance 'this'
  },
  beforeRouteLeave (to, from, next) {
    // called when navigating away from the component's corresponding route
    // Access component instance 'this'}}Copy the code
  • Pay attention to the point:beforeRouteEnterIs the only guard that supports passing a callback to next. forBeforeRouteUpdate and beforeRouteLeaveThis is already available, so passing callbacks are not supported because they are not necessary.
// The component instance can be accessed by passing a callback to next. The callback is executed when the navigation is validated, and the component instance is taken as an argument to the callback method
beforeRouteEnter (to, from, next) {
  next(vm= > {
    // Access component instances through 'VM'})}Copy the code

3. Complete navigation parsing process

1.Navigation is triggered.2.Called in a deactivated component`beforeRouteLeave`The guards.3.Call global`beforeEach`The guards.4.Called in a reused component`beforeRouteUpdate`Guard (2.2+).5.Called in the routing configuration`beforeEnter`.6.Parse the asynchronous routing component.7.Called in the active component`beforeRouteEnter`.8.Call global`beforeResolve`Guard (2.5+).9.Navigation confirmed.10.Call global`afterEach`Hook.11.Trigger a DOM update.12.call`beforeRouteEnter`The created component instance is passed in as an argument to the callback function passed to Next in the guard.Copy the code

keep-alive

1. Keep-alive is basically used

  • Background: For example, if we click on the home page (there are two sub-components under the home page, the News component and the Messages component), the default display is /home/news under the home page. Then we click on the Messages component, and the display is /home/messages. At this time, we click the sibling component of the home component /home/about, and then we click the home component. At this time, the home component is not the status messages component that is stopped before we go to the About component, but the default rendered news component of the home component, indicating that the previous state has not been retained. Switching from the About component to the Home component recreates the home component and re-renders it.

  • Keep-alive: is a built-in component of Vue that allows wrapped components to remain in state or avoid re-rendering. This means that when you cut back to the component again, it will not be recreated or rendered

  • Router-view: a built-in component of vue-router. If it is directly wrapped in keep-alive, all view components matched by the path will be cached.

  • Activated&deactivated: These two lifecycle functions are only effective if keep-alive wraps the component. When switching a routing component, the deactivated function is invoked when the wrapped component is in the active state. When switching another component, the deactivated function is invoked when the wrapped component is in the inactive state.

  • Address background issues:

<! -- -->
<! -- app. vue: Modify render home component exit -->
<keep-alive>
    <router-view />
</keep-alive>
Copy the code
// Home.vue
export default {
  template: '#home',
  data () {
    return {
      // Delete the nested path from the route of the news component displayed by default on the home page configured in. Set path in the home component to the path of the subcomponent displayed by default
      path: '/home/news'}},// activated is a lifecycle function called when the component is active. This works only if the keep-alive component is wrapped;
  activated () {
    // This. Path is the content of the news component when executed the first time.
    this.$router.push(this.path).catch(err= > { err })
  },
  // The navigation guard hook function within a component is called when leaving the corresponding route of the component.
  beforeRouteLeave (to, from, next) {
    // Record the path of leaving the component to this.path so that the next time the component is active, the call activated will show the state of the component before leaving
    this.path = this.$route.path
    next()
  }
}
Copy the code

2. Keep-alive other attributes

Keep-alive defaults to caching all wrapped components

  • include: string or regular expression. Only matching components are cached. That requires an associated componentnameAttribute combination
  • exclude: string or regular expression, any matching components will not be cached. That requires an associated componentnameAttribute combination
// Problem 1: If you do not want to cache one of the components, you can use exclude

// app. vue: Because the exit is from the router-view wrapped by keep-alive in app. vue, all components are cached by default.
<keep-alive >
    <router-view />
</keep-alive>

// Exclude ="Profile,User" exclude="Profile,User"; The string component specified in exclude is associated with the component's name property. Note that there should be no Spaces on either side of comma-connected components
// App.vue
<keep-alive exclude="Profile,User">
    <router-view />
</keep-alive>

// Profile.vue
export default {
  template: '#profile'.name: 'Profile',}// User.vue
export default {
  template: '#user'.name: 'User',}Copy the code

Command routing

  • Configure the name attribute for route. You can use name instead of path in other places, so you don’t need to write such a long path
/ / sample:
// /router/index.js
const router = new VueRouter({
  routes: [{path: '/user/:userId'.// The name attribute configures the command route
      name: 'user'.component: User
    }
  ]
})

// Both methods navigate the route to '/user/123'. Note that to is preceded by the colon binding
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
router.push({ name: 'user'.params: { userId: 123 }})
Copy the code

Named view

  • Named view: Sometimes you want to present multiple views simultaneously (at the same level) rather than nesting them, for example to create a layout, there aresidebar(Side navigation) andmain(Main content) two views, this is where the named view comes in handy. Instead of having a single exit, you can have multiple individually named views in the interface. ifrouter-viewIf no name is set, the default isdefault.
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
Copy the code

A view renders with one component, so multiple views require multiple components for the same route

const router = new VueRouter({
  routes: [{path: '/'.components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})
Copy the code

Redirects and aliases

  • redirect: When the user accesses/a, the URL will be replaced by/b, and matches the route as/b
  • The alias:/aThe alias is/bMeans when the user accesses/b, the URL remains as/b, but the route match is/a, like user access/aThe same.
// Redirection is also done with the Routes configuration, as shown in the following example redirecting from /a to /b
const router = new VueRouter({
  routes: [{path: '/a'.redirect: '/b'}]})// The redirection target can also be a named route:
const router = new VueRouter({
  routes: [{path: '/a'.redirect: { name: 'foo'}}}])// Even a method that dynamically returns the redirected target
const router = new VueRouter({
  routes: [{path: '/a'.redirect: to= > {
      // The method receives the destination route as an argument
      // Return redirects the string path/path object}}}])Copy the code
// Example: Alias: Two paths correspond to one route
const router = new VueRouter({
// The path '/fxxksky' and '/two-dogs' both jump to A
  routes: [{path: '/fxxksky'.component: A, alias: '/two-dogs' }
	Alias: ['/two-dogs', 'three-dogs','four-dogs','five-dogs'] alias: ['/two-dogs', 'three-dogs','four-dogs']]})Copy the code

Routing meta information

  • Some information can be stored, such as user login authentication.
/ / sample:
const router = new VueRouter({
  routes: [{path: '/foo'.component: Foo,
      children: [{path: 'bar'.component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})


router.beforeEach((to, from, next) = > {
  if (to.matched.some(record= > record.meta.requiresAuth)) {
	// Array some method, which returns true if meta. RequiresAuth is true. In this case, you need to check whether the user has logged in before entering the route
    if(! auth.loggedIn()) {// If you are not logged in, jump to the login page
      next({
        path: '/login'.query: { redirect: to.fullPath }  // This is a nice little detail in the official example. Query saves the route path to jump to. After login, you can get the path directly and jump to the route to go to before login})}else {
      next()
    }
  } else {
    next() // Be sure to call next()}})Copy the code

HTML5 history mode

The History interface allows you to manipulate the browser’s session History that has been accessed in tabs or frames

  • Common properties and methods:
    • History.length: Number of urls visited by the current window (including the current page)
    • History.back(): Go to the previous page, and the user can simulate this method by clicking the back button in the upper left corner of the browser. Equivalent to the history. The go (1)
    • History.forward(): To go to the next page in browser history, the user can simulate this method by clicking the Forward button in the upper left corner of the browser. Equivalent to the history. The go (1)
    • History.go(): Loads the page from the browser history (session record) by relative position of the current page. For example, if the parameter is -1, the previous page is displayed. If the parameter is 1, the next page is displayed

H5 New method history.pushState()

history.pushState(state, title, url); Add a history without refreshing the page

  • history.pushState(state, title[, url]): Adds a state to the history stack of the current browser session.
  • parameter:
State: a state object associated with the specified url that is passed into the callback function when the popState event is triggered. If you don't need this object, you can fill it in herenull.title: The title of the new page, but all browsers currently ignore this value, so it can be filled in herenull.url: new url, must be in the same domain as the previous page. The browser's address bar will display the url.Copy the code
// The browser did not reload demo.html, just changed the browser address bar address
// index.html
history.pushState(null.null.'./demo.html')
history.pushState(null.null.'./inexistence.html')

// apply -- add hash values and the page is only partially loaded
// index.html
history.pushState(null.null.'#one')
Copy the code

H5 New method history.replacEstate ()

history.replaceState(state, title, url); Replaces the current history without refreshing the page

//demo.html
history.replaceState(null.null.'? one') Current history HTTP://localhost/class/demo.htmlReplaced with HTTP://localhost/class/demo.html? one
Copy the code
1.Popstate event: Triggered when the history changes. A call to history.pushState() or history.replacEstate () does not trigger a popState event2.Hashchange event: Triggered when the hash value of a page changes, often used to build single-page applications.Copy the code

Route lazy loading

Lazy load implementation of routing components: a combination of Vue’s asynchronous components and Webpack’s code splitting feature

JavaScript packages can become very large when packaged to build applications, affecting page loads. It would be much more efficient if we could split the components corresponding to different routes into different code blocks and then load the components only when the routes are accessed.

// The following approach defines asynchronous components that can be partitioned automatically by Webpack code
const Foo = () = > import('./Foo.vue')
Copy the code