preface

About the title, should not be the title party, because the content is really a lot of long and comprehensive. Mainly on the basis of the official website and detailed summary, a lot of things for example. Make sure all new people understand! So a lot of things are actually more detailed than the official website. What you want, did not understand on official website, basic can find a solution here! I was going to split it up into two posts, but there’s nothing wrong with a longer man. So I hope you can collect the eye tag (funny)

Features: This article is based on official documents. With the exception of the less commonly used transient effects and data acquisition, all are analyzed. Description: Each section provides a more general explanation on the basis of the documentation; Examples: Each section has a separate example added for detailed explanation, and there is a detailed explanation for anything that is not officially available or complex or skipped. Summary: Each section contains tips, practical development experiences, and summaries.

Usage:

If you’re new to VueRouter, start at the very beginning. The first five chapters have been designed to familiarize you with VueRouter step by step, and chapter 5 also gives examples of code that you can actually build locally.

If you know more about VueRouter, you can choose to view it according to the directory. Or global search keywords to quickly locate.

Jokingly: Most articles about VueRouter that can be found now are copies of official documents. Very disgusted with this article! Basically not much nutrition! What you don’t understand on the official website, he basically can’t understand.

1, an overview of the

Vue-router and vue.js are deeply integrated and suitable for single-page applications. Traditional routing is to use some hyperlinks to achieve page switching and jump. Vue-router, on the other hand, switches between components in a single-page application. In essence, it creates and manages mappings between urls and corresponding components.

2. Simple examples

Here is a simple example from the official website to understand the components of the Vue-router, and have a preliminary impression of the Vue-router.

HTML

First, the HTML part. There are two main functions:

1,router-link component to navigate, users click to switch to the relevant view.

2,router-view component to set where the toggle view is rendered.(A page can also have multiple router-views displaying a specific view, and can be nested.)

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Hello App!</h1><p> <! -- Use router-link component to navigate. --> <! -- specify the link by passing in the 'to' attribute. -- <router-link> is rendered as a '<a>' tag by default --> <router-link to="/foo">Go to </router-link> <router-link to="/bar">Go to Bar</router-link> </p> <! -- Route exit --> <! </router-view> </div> </div>Copy the code

JavaScript

See chapter 5 later for the actual project code. I will briefly summarize the following steps:

  • 1. Material preparation:
    • 1.1 Introduce ready ‘Vue’ and ‘vue-Router ‘(if already NPM)
    • 1.2 Importing components of route hops. Here’s an example of ‘Foo’ and ‘Bar’
    • 1.3 Starting the global component VueRouter Example: vue.use (VueRouter). Then the Vue-router is executed.
  • New VueRouter() can be used to configure routing instances, such as the path of each route, the corresponding components, and so on.
  • New Vue({router}).$mount(‘#app’)
// 0\. To import Vue and VueRouter using modular programming, call vue.use (VueRouter)

// 1\. Define (routing) components.
// Import from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2\. Define the route
// Each route should map one component. Where "component" can be
// The component constructor created with vue.extend (),
// Or, just a component configuration object.
// We will discuss the nested methods later.
const routes = [
  { path: '/foo'.component: Foo },
  { path: '/bar'.component: Bar }
]

// 3\. Create a router instance and pass the 'routes' configuration
// You can also pass other configuration parameters, but that's easy for now.
const router = new VueRouter({
  routes // (abbreviated) routes: routes
})

// 4\. Create and mount the root instance.
// Remember to configure router parameters to inject routes,
// So that the entire application has routing capability
const app = new Vue({
  router
}).$mount('#app')

// Now the application is started!

Copy the code

$route: this.$route: this.$route: this.$route: this.

$route = $router; $route = $route;

  • $routerRefers to the entireRouting instanceYou can manipulate the entire route by adding arbitrary routing objects to it by ‘$router.push’.
  • $route: refers to the route to which the current instance (‘$router’) hopsRoute objects;
  • A route instance can contain multiple route objects. They are parent-child inclusion relationships.
// Home.vue
export default {
  computed: {
    username() {// We'll soon see what 'params' isreturn this.$route.params.username
    }
  },
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')}}}Copy the code

3. Vue-router schematic relationship (if there is a problem, it needs to be modified)

In the image, router-js is the route instance configuration file

PS:
See the official TO API for details.

4, study preparation! important

4.1 Preparing Hardware

To learn something new, just look and think. Well, it looks something like this. It’s not going to have any effect. You don’t know anything unless you’ve actually tapped it or used it. Therefore, it is highly recommended that you watch and knock while thinking and summary. Here are two ways:

  • Official website online instance: click here through the online instance, according to the tutorial side to see while tapping!
  • Use my tutorial in Chapter 5 to build on your own local real project and see how it works.

Both are fine. Personally, I suggest you choose the second option conditionally, which is more intuitive and more close to your actual project needs.

4.2 Mental Preparation

To configure the Vue-Router, consider two aspects:

  • Html: corresponds to the vue-router<router-link>and<router-view>
  • JavaScript: is the configuration of the specific routing instance. The configuration of the vue-Router is also carried out around these two levels. When learning, we must have this awareness, so that it is easier to understand and use!

5. Examples of actual project construction

5.1, download vue-Router:

	npm i vue-router -s
Copy the code

5.2. Configure router-link and router-view in vUE

  • Router-link: indicates the route mapping. Create a tag to define the link to the route navigation (the user can click to jump). The target address is specified through the TO attribute. By default, the tag is rendered with the correct link.
  • Router-view: The router-view is the view component that your route matches within the label. Router-view supports nested router-views, and multiple router-Views can be used to render different components. Click the Document Name view for details.
<! -- Here is the official example -->
<div id='app'>
	<p>
		<router-link to="/user/foo">/user/foo</router-link>
		<router-link to="/user/bar">/user/bar</router-link>
	</p>
	<router-view>The contents of the router-view will not be displayed on the page!</router-view>
</div>
Copy the code

For more details on the use of TO: see the official API documentation. It’s very simple and I won’t repeat it here.

5.3. Configure the router-js file of the route instance

// Step 1: Import the necessary files
import Vue from 'vue';// Import Vue when loading global components
import Router from 'vue-router';Vue / / in the router
// Import components needed for routing
import User from '@/components/user/User' // The.vue is omitted.// Step 2: Load Router
Vue.use(Router);// Load the global component Router

// Step 3: Configure the route instance
export default new Router({
	// Mode :'history', // Routing mode: default hash, if you change to history, you need to work with the back end
	/ / base: '/', / / base path: the default value is'/'. If the whole single page application under the/app/base should be set to '/ app/'. This can be written as __dirname and configured in WebPack.
	routes:[{
		path: '/user'.name: 'user'.// Give the route a unique name.
		component: User// is the component imported in the first step}, {// Lazy route loading: it takes a long time to load the content on the home page of a single-page application. Use lazy loading to divide the page components to reduce the loading time of the home page
			path:'/Page'.name:'Page'.component:resolve= > require(['@/components/Page'],resolve)
			// In this case, the Component does not need to import in the first step}]})Copy the code

In 5.4, introduce router. Js in main.js and mount it to the Vue instance

In real projects, it is recommended to configure the router in a separate JS file, which is more clear. Do not mix the router configuration in main.js.

import router from './router'

new Vue({
  el: '#app',
  router,// Router :router,
  store,
  template: '<App/>'.components: {
  App

  } })
Copy the code

Router,routes,route

  • 1. Router: Generally refers to a route instance. Such as $router.
  • 2, routes: Routes API of the router route instance. This command is used to configure multiple routes.
  • 3, route: refers to the route object. For example; $route refers to the current route object.

5.6, the summary

At this point, a basic Vue-router is complete. Here is a simple demonstration of how to do it. To summarize, when writing a vUE route, remember to do the following three things: 1, prepare: import router. Js in main.js to mount the vue instance. 2, configure the route instance (important): Import Vue and vue-router into router-js to configure the routing instance. 3, component configuration: configure router-link and router-view.

6. Two modes of vue-router

The vue-Router provides two ways to implement front-end routing :Hash mode and History mode. You can use the mode parameter to determine which mode to use.

6.1, Hash pattern

Vue-router uses the Hash mode by default. Use the URL hash to simulate a complete URL. When the URL changes, the browser does not reload. The Hash(#) is the anchor point of the URL and represents a location on the page. Simply changing the Hash will cause the browser to scroll to the location and not reload the page. It will not be included in the HTTP request, so the page will not be reloaded. When the hash changes, the URL is recorded by the browser, so you can use the browser’s back.

To summarize: The Hash mode is to enable the browser to render the specified component by changing the value after #.

6.2, the History mode

If you don’t like hash # style. You can use the History mode. This pattern takes advantage of the new pushState() and replaceState() methods in HTML5 History. In addition to the previous back,forward, and go methods, these two new methods can be applied to add replacement functionality to the browser history. Using the History pattern, the URL is modified through the History, but it does not immediately send the request back end. Note: While History mode can throw away unsought-after # tags and move back and forth normally, after refreshing F5, the browser will access the server and get a 404 without background support! The official description reads :” This mode, however, requires background configuration support to play well. Since our application is a single client application, if the background is not configured correctly, a 404 will be returned when the user accesses it directly. So, you need to 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.”

In summary :History mode is the pushState() method used to modify the browser's browsing History so that it does not require the backend to render. However, it is recommended that you use the History mode for the actual project.

Example:

const router = new VueRouter({
  mode: 'history'.// If not, the route defaults to hash mode
  routes: [...]
})
Copy the code

7. Dynamic route matching

It is often necessary to match a pattern to all routes, all of which map to the same component. For example, we have a User component that is used to render all users with different ids. At this point we can configure the dynamic routing implementation. Dynamic route matching is essentially passing parameters through urls

7.1. Route Object Properties:

This.$route(not $router!) can be used within a component. Conduct interviews.

$route.path Type: string A string that corresponds to the path of the current route and is always resolved to an absolute path, such as “/foo/bar”.

$route.params type: Object A key/value Object that contains dynamic fragments and fully matched fragments, or an empty Object if there is no route parameter.

$route.query type: Object A key/value Object that represents the URL query parameter. For example, for the path /foo? If user=1, then $route.query.user == 1. If there is no query parameter, then it is an empty object.

$route. name Specifies the name of the current route, if any. It is recommended to give each routing object a name to facilitate future programmatic navigation. Remember that the name must be unique!

Hash type: string Hash value of the current route (with #), or an empty string if there is no hash value.

$route.fullPath type: string parsed URL, including the fullPath of query parameters and hash.

$rout. matched type: Array

An Array containing routing records for all nested path segments of the current route. The route record is a copy of the object in the Routes configuration array (and also in the Children array). $route.redirectedFrom Specifies the name of the route from which the redirection originated, if any.

7.2 Configuring using Params:

Here’s an example:

routes:[{
	// Dynamic path parameters, starting with a colon
	path:'/user/:id'.component:User
}]
Copy the code

In this case, you use Params to configure. Things like /user/foo and /user/bar will map to the same route.

  • A path parameter is marked with a ‘:’ colon.
  • When a route is matched, the parameter is set tothis.$route.paramsCan be used within each component. For example/user/foo inthis.$route.params.idFor the foo

The official table example is shown here

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 }

Here’s a slightly different example to help you understand:

routes:[
	{path:'/user/:shot/foo/:id'.component:shotCat}
]
Copy the code
<p>
	<router-link to="/user/shot/foo">/user/shot/foo</router-link>  	<! -- Failed to match the corresponding route -->	
	<router-link to="/user/shot/cat/foo">/user/shot/cat/foo</router-link>	<! -- Failed to match the corresponding route -->	
	<router-link to="/user/foo/foo/foo">/user/foo/foo/foo</router-link>	<! -- Match successfully,$rout.params. shot is foo; $route. Params. The cat is foo; -->	
	<router-link to="/user/shot/foo/cat">/user/shot/foo/cat</router-link><!--成功匹配,$route.params.shot为shot;$route.params.cat为cat;-->	
</p>
<router-view></router-view>
Copy the code

tips:

  • Sometimes, the same path can match multiple routes. In this case, the matching priority is based on the route definition order. Whoever defines it first has the highest priority.
  • Because routing parameters are multiplexed to component instances. Such as:/user/foo 和 /user/barWhen using routing parameters, the multiplexing isUserComponent. 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 inside the component$routeObject:
    const User = {
     template: '... '.watch: {
       '$route' (to, from) {
         // Respond to routing changes...}}}Copy the code
    • Use the beforeRouteUpdate route guard in version 2.2:
    const User = {
      template: '... ',
      beforeRouteUpdate (to, from, next) {
    	// react to route changes...
    	// don't forget to call next()}}Copy the code

7.3. Use query to pass parameters for configuration.

In the project we can pass parameters through the params mentioned above. You can also pass parameters using query. For example:

foo
The following id=foo is encapsulated in this.$route.query. $route.query.id == in addition to the to attribute of the router-link, query can also be passed through the programmatic navigation described below

8, programmatic navigation

$router-link :to>

Of course, this assumes that you have configured the routing object in routes.

When do you normally use programmatic navigation? If, for example, you want to do something else before the route jump, such as permission verification. But if you use

, you just jump to it. Now you can use programmatic navigation!

8.1, programmatic navigation writing

The router-push method is usually used for programmatic navigation. The argument to this method can be a string path or an object describing the address. Such as:

/ / string
this.$router.push('home')

/ / object
this.$ruter.push({path:'home'})

// Name the route
this.$router.push({name:'user'.params: {userId:2333}})

// With query parameters, change to /register? plan=private
this.$router.push({path:'register'.query: {plan:'private'}})

Copy the code

Note :== forgive color warning ==:path and params cannot work together! Otherwise params will be ignored. So when you pass params using object writing, it’s either path plus a colon :, or ‘named route’ as in the example above. Pass parameters by name and params. Query, however, is unaffected and can be passed with or without a path.

8.2, the router. The replace method

Router. replace is similar to router.push. It’s written the same way. But the actual effect is different. Push isto add a new record to history. Replace simply replaces the current browser history record!

What are the immediate consequences? Here’s an example:

  • With the push method, page 1 goes to page 2, and you can use the browser’s back to go back to page 1
  • With the replace method, page 1 is replaced with page 2, and you use the browser’s back. At this point, you can’t go back to page 1. You can only go back to the page before page 1, page 0.

When do we use replace? Permission authentication is common when you don’t want the user to go back to the previous page, and then don’t let the user go back to the login page to repeat the authentication.

8.3, the router. The go (n) method

The argument to this method is an integer, which means how many steps forward or backward in the history record. Something like window.history.go(n). This allows you to control how many steps the page can take forward or backward.

9. Additional summaries related to dynamic routing and programmatic navigation:

Add: In fact, you can also use the following method to directly pass parameters on the router-link without configuring routes. For more details on the use of TO: see the official API documentation. It’s very simple and I won’t repeat it here.

routes:[
	{name:'shotCat'.path:'/shotCat'.component:shotCat}
]
Copy the code
<router-link :to="{ name:'shotCat',params:{paramId:'hello'},query:{queryId:'world'}}">helloWorld</router-link> <! In this case, the route object shotCat is matched by name.-->	 
<router-link :to="{ path:'/shotCat',params:{paramId:'hello'},query:{queryId:'world'}}">helloWorld</router-link>  <! -- At this point, the route object shotCat is matched by path. But!!!!! In this case, 'paramId' cannot be added to '$rout.params', only' queryId 'can be added to' $rout.query '-->
Copy the code

This is the same as the rules for programmatic navigation. Path and params do not work together! So it’s best to give each routing object a name! ** Query: path and name can be passed. {{$route.params}} and {{$route.query}} are passed successfully. Summary:

  • 1,<router-link :to="{ }">Is equivalent tothis.$router.psh(). pathandparamsCan’t exist simultaneously!To pass params, you need to add the name attribute.queryNot affected.
  • 2,<router-link :to="{ }">andthis.$router.psh()The actual effect is the same.
    • 2.1 Params parameters are not displayed in the URL address bar. Except for those configured through routes in the routing. So when the user refreshes the page, the params parameter is lost!
    • 2.2 Query parameters can be displayed in the URL address bar. It will not be lost after refreshing the page

Params and query can be passed through to. But notice that the page URL doesn’t change! So when you refresh the page, the parameters are gone.

10 Embedded sets consist of multiple views with single component

  • The parent route is nested with subroutes. The url is /user and the two subroutes are /user/foo and /uer/bar. Represented by a graph:

  • Multiple views per componentMultiple views are displayed in a component. That is, there are multiple<router-view/>

10.1 Embedded sets by

Before we go into this, it’s important to know that a
represents a component, so there are two main points to implementing nested routines:

  • Define subroutes in routing objects (nested subroutes)
  • In the component<router-view/>The use of.

These two points also correspond to my note on mental preparation in Chapter 4.

Below my example or the above figure set by example to explain. You can see the official example is an example of nested routes used by collocation dynamic routing, you can modify on this basis to try.

10.1.1 Define child routes in route objects

const router = new VueRouter({
  routes: [{path: '/user'.component: User,name:'user'.// The children configuration is written as rutes.
      children: [
        { path: ' '.component: UserDefault ,name:'default'.//children:[{}] can also continue to add children nesting
		},
		// If /user does not match any subroutes, user 
      
        will display nothing if you want it to. You can set path: ". To null. In this case, UserDefault is the default component displayed.
      
		
        { path: 'foo'.component: UserFoo,name:'foo'},
		// In this case, path is the same as '/user/foo', and the child route inherits the path of the parent route. However, you cannot write path:'/foo' because nested paths beginning with/are considered the root path, meaning that foo becomes the root path. Instead of the user.
		
        { path: 'bar'.component: UserBar,name:'bar'}]}]}Copy the code

10.1.2 kit<router-view/>The use of.

<div id="app">
 <p>
   <router-link to="/user">/user</router-link>
   <router-link to="/user/foo">/user/foo</router-link>
   <router-link to="/user/bar">/user/bar</router-link>
 </p>
 <router-view></router-view> <! -- The User component shown here; The User <router-view/> is also nested inside -->
</div>
Copy the code
const User = {
 template: ` 
      

User

`
} //User shows the child route foo,bar component and default component const UserDefault = { template: '<div>default</div>' } const UserFoo = { template: '<div>foo</div>' } const UserBar = { template: '<div>bar</div>' } Copy the code

10.2 Single component with multiple views

If a component has multiple views, show multiple child components. This is where you need to use the official online example of named views, which you can try out on your own. Let’s go straight to my example:

<div id="app">
 <h1>Named Views</h1>
 <p>
   <router-link to="/avenger">The Avengers</router-link>
 </p>
 <router-view ></router-view>
 <router-view name="ironMan"></router-view>
 <router-view name="captainAmerica"></router-view>
</div>
<! Here we name two of the views ironMan and captainAmerica; If you don't set name, you get a view named default>Copy the code
const router = new VueRouter({
  routes: [{path: '/avenger'.name:'avenger'.components: {
        default: stanLee,
        ironMan: ironMan,
        captainAmerica: captainAmerica
      }
	// If more than one view needs to be displayed, replace the previous Component with components(plus s!!). , in object form. 
      
        set name="ironMan"; The one on the right refers to the ironMan component below.
      }]})const stanLee = { template: '
      
'
} const ironMan = { template: '
'
} const captainAmerica = { template:
Captain America
} Copy the code

Nested Named Views: an official online example that combines nested and named views. It’s just a combination of the two. Beginners are advised to use this example to further their understanding.

11 Redirects and aliases:

11.1 Redirection Configuration:

Redirection is actually through routing. Intercept the PATH and redirect to the route specified by the Redirect instead of the URL. Redirection is done through routes configuration,

// Redirect from /a to /b
const router = new VueRouter({
	routes:[
		{path:'/a'.redirect:'/b'}]})/// Redirect from /a to a route named 'foo'
const router = new VueRouter({
  routes: [{path: '/a'.redirect: { name: 'foo'}}}])// Even a method that dynamically returns the redirection target:
const router = new VueRouter({
  routes: [{path: '/a'.redirect: to= > {
      // The method accepts the destination route as a parameter
      // return redirected string path/path object
	  const { hash, params, query } = to
	  // The hash mode of to,params, and query parameters are used in ES6. I won't go into the details of the deconstruction here.
        if (query.to === 'foo') {
          return { path: '/foo'.query: null}}if (hash === '#baz') {
          return { name: 'baz'.hash: ' '}}if (params.id) {
          return '/with-params/:id'
        } else {
          return '/bar'}}}}])Copy the code

11.2 the alias

Redirection is to change the path for the URL to reach the route jump. The alias is a route that has two paths. Both paths can jump to this route. For example, your first name might be ‘Zhao Ri Tian ‘, but your nickname might just be’ Er Gou zi ‘. But ‘Zhao Ri Tian’ and ‘Er Gou zi’ refer to the same person (routing). The alias is configured as the alias in Rutes:

const router = new VueRouter({
// In this case, both '/fxxksky' and '/two-dogs' jump to A
  routes: [
    { path: '/fxxksky'.component: A, alias: '/two-dogs' }
	Alias: ['/two-dogs', 'three-dogs','four-dogs','five-dogs'] alias: ['/ three-dogs','four-dogs','five-dogs']]})Copy the code

12 Route components pass parameters

Route passes parameters, which can be passed through params and Query as described earlier. But in both cases, you essentially put the parameter on the URL, and you change the URL. This results in a high degree of coupling between parameters and components. If I want to pass arguments, I can be more free, I can get rid of the URL. At this point, you can use the props for rute to decouple. Improves component reuse without changing the URL.

PS: This part of the official online instance, you can be my following example of the code will be covered before the online example can be

// Route configuration:

const Hello = {
  props: ['name'].// When passing the props of rute, the corresponding component must add props to receive the props. Otherwise, no props can be passed
  template: '< div > Hello {{$route. The params}} and {{this. The name}} < / div >'
  // If this.name has a value, then name has successfully become a property of the component
}

const router = new VueRouter({
mode: 'history'.routes: [{path: '/'.component: Hello }, // No parameters were passed, so the component gets nothing
    { path: '/hello/:name'.component: Hello, props: true }, // Boolean mode: props is set to true, and rout. params (name here) will be set as a component property.
    { path: '/static'.component: Hello, props: { name: 'world' }}, // Object mode: Params has nothing to do with it. The name is passed directly to the Hello component. Note: Props must be static!
    { path: '/dynamic/:years'.component: Hello, props: dynamicPropsFn }, // Function mode: 1, this function can take one argument by default, that is, the current route object.2, this function returns an object.3, in this function you can handle static values related to the route.
    { path: '/attrs'.component: Hello, props: { name: 'attrs'}}}])function dynamicPropsFn (route) {
  return {
    name: (new Date().getFullYear() + parseInt(route.params.years)) + '! '}}new Vue({
  router,
  el: '#app'
})
Copy the code
<! - HTML part -- -- >
    <div id="app">
      <h1>Route props</h1>
      <ul>
        <li><router-link to="/">/</router-link></li>
        <li><router-link to="/hello/you">/hello/you</router-link></li>
        <li><router-link to="/static">/static</router-link></li>
        <li><router-link to="/dynamic/1">/dynamic/1</router-link></li>
        <li><router-link to="/attrs">/attrs</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
Copy the code

13 Routes are lazily loaded

Vue is mainly used for single-page applications. At this time, WebPack will pack a large number of files, which will cause the home page to load too many resources, the first screen time is too long, and give users a unfriendly experience. If you use lazy route loading, the relevant page is only loaded when you route the jump. The lazy loading of vueRouter is mainly based on Vue’s asynchronous components and Webpack’s code segmentation function, which can easily realize the lazy loading of routing components. This is what I did in the example in Chapter 5.3, and it’s easy to introduce components in the form of promises.

routes:[
      path:'/'.name:'HelloWorld'.component:resolve= >require(['@/component/HelloWorld'],resolve)
  ]
  // The HelloWorld component does not need to be imported in the first step
Copy the code

13.1 Divide the components into components

By grouping components into component blocks, all components under the route can be packaged into the same chunk, and dynamically loaded component names can be seen in the NETWORK of F12. Prerequisites:

  • Webpack Version > 2.4
  • We need to add chunkFileName below the filename in the output of webpack.base.conf.js
output: {
 path: config.build.assetsRoot,
 filename: '[name].js'.// Where configuration is required
 chunkFilename: '[name].js'.publicPath: process.env.NODE_ENV === 'production'
   ? config.build.assetsPublicPath
   : config.dev.assetsPublicPath
}
Copy the code

When the component is introduced, it is written using the name chunk. A special annotation syntax provides the chunk name

const Foo = (a)= > import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = (a)= > import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = (a)= > import(/* webpackChunkName: "group-foo" */ './Baz.vue')
Copy the code

14 Navigation Guard

Route navigation guards, or, colloquially, route hooks. It also acts as a life cycle hook to control the operation of the route jump process. The navigation guard has a lot of hooks, so I won’t copy the official document here. Click here to read the navigation Guard, and then see my summary and code examples.

14.1 Navigation Guard Classification

  • 1, global guard:: Asynchronous execution. Each route jump is executed in sequence.
    • Router. beforeEach Global front guard
    • The Router. beforeResolve Global Resolution Guard (2.5.0+) is called after the beforeRouteEnter call.
    • Router.aftereach ((to, from) => {});

Each guard method takes three arguments:

  • To: Route: indicates the destination Route object to be entered

  • From: Route: Route object that the current navigation is leaving

  • Next: Function: Be sure to call this method to resolve the hook. The execution effect depends on the call parameters to the next method.

    • Next (): Makes the next hook in the pipeline. If all hooks have been executed, the state of the navigation is confirmed.

    • Next (false): Interrupt the current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL will be reset to the address of the FROM route.

    • Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is made. You can pass any location object to next and allow options such as replace: true, name: ‘home’ and any options used in the Router-link’s to prop or router-. push.

    • Next (error): (2.4.0+) If the argument passed to next is an error instance, the navigation will be terminated and the error will be passed to the registered callback of router.onError().

The official introduction is relatively simple, there is no actual chestnuts, below I will be through chestnuts to explain in detail

//1, which can be set either in main.js or in a separate route configuration file route.js
	router.beforeEach((to, from, next) = >{... next(); });//2, can also be set inside the component
	this.$router.beforeEach((to, from, next) = >{... next(); });//3, detailed instructions for the function and next()
    router.beforeEach((to, from, next) = > { 
	To and from are actually a route object, so the attributes of the route object are available (see the official ROUTE object API documentation for details).
	// For example: I want to get to the full path is to.path. Get to the child route to.
      next();// Do not omit next!!
	//next() goes straight to the next hook.
	//next(false) Interrupt the current navigation
	//next('/path path ') or object next({path:'/path path '}) jumps to the path route address
	//next({path:'/shotcat',name:'shotCat',replace:true,query:{logoin:true}... Router-link to prop; router-link to prop; router-link to prop In this case,replace:true means to replace the current routing address. This is often used to modify routes after permission is determined.
	//next(error),(2.4.0+)
    }).catch((a)= >{
  // The failure page is displayed
  next({ path: '/error'.replace: true.query: { back: false}})})// If you want to jump to the error and do something else with the callback you can use router.onError()
router.onError(callback= > { 
      console.log('Wrong! ', callback);
    });
Copy the code
  • 2, route exclusive guard:That is, a guard exclusively owned by the routing object
    • BeforeEnter: Routes only have this hook, configured in rutes
const router = new VueRouter({
  routes: [{path: '/foo'.component: Foo,
      beforeEnter: (to, from, next) = > {
        // Use the same method as beforeEach}}}])Copy the code
  • 3. Guards inside components:Note: This type of routing hook is written inside the component.
    • Before beforeRouteEnter enters the route, the instance has not been created, and the ZHIS cannot be obtained
    • BeforeRouteUpdate (2.2) When routing is multiplexed with the same component
    • BeforeRouteLeave leaves the current route and can be used to save data, initialize data, turn off the timer, and so on

Here the official example is very detailed, here is the direct quote.

// This function is configured inside the component. This function is used the same way as beforeEach
const Foo = {
  template: `... `,
  beforeRouteEnter (to, from, next) {
    // Called before the rendering component's corresponding route is confirmed
    / / no! Can!!!! Get component instance 'this'
    // Because the component instance was not created before the guard executed
  },
  beforeRouteUpdate (to, from, next) {
    // called when the current route has changed but the component is being reused
    // For example, for a path with dynamic parameters /foo/:id, jump between /foo/1 and /foo/2,
    // Since the same Foo component is rendered, component instances are reused. The hook will be called in that case.
    // Can access component instance 'this'
  },
  beforeRouteLeave (to, from, next) {
    // called when navigating away from the corresponding route of the component
    // Can access component instance 'this'}}Copy the code

14.2 Complete navigation parsing process

The instructions given by the official documents are written and not particularly intuitive. There’s no copy here. Here is directly in the form of a flow chart to show (here refer to the student’s picture, thank you!) .

15 Route metadata

15.1 What Is Routing Meta Information

In short: information in the Meta object of the route configuration. Official chestnuts:

const router = new VueRouter({
  routes: [{path: '/foo'.component: Foo,
      children: [{path: 'bar'.component: Bar,
          // a meta field
          meta: { requiresAuth: true}}]}]})Copy the code

We added a custom meta object to the route and set the state of requiresAuth to true.

15.2 What does it do

The answer is already given in another official chestnut below.

router.beforeEach((to, from, next) = > {
  if (to.matched.some(record= > record.meta.requiresAuth)) {
    // If you don't know about matched, see the official API documentation, or my description in section 7.1
	// The some method of the array returns true if meta-.requiresauth is true. In this case, check whether the user has logged in before entering the route
    if(! auth.loggedIn()) {// If you are not logged in, go to the login page
      next({
        path: '/login'.query: { redirect: to.fullPath }  // This is a nice little detail in the official example. The query saves the route path to jump to. After logging in, you can directly get the path and jump directly to the route you want to go to before logging in})}else {
      next()
    }
  } else {
    next() // Make sure to call next()}})Copy the code

We can determine whether login authentication is required by setting the status in the Meta. If requiresAuth in the meta is true, we need to determine whether we are logged in, and if we are not logged in, we jump to the login page. If you have logged in, the jump continues.

At this point, some of you might say, “Path,params,query can all store information as a status marker for login verification.” Indeed, they can do the same thing. If you have a small number of individual validations, you don’t have a problem using them. But what if multiple routes require login authentication? Path, Params, and Query store information explicitly on the URL. And multiple paths add the same state information to the URL. This makes the URL not simple, and it is not elegant and beautiful. So to pass information gracefully and implicitly, use meta objects!

16 Rolling behavior

ScrollBehavior is used when switching routes to make the page scroll to where you want it to be, or when you want it to stay where you want it to be.

Note:

  • The scroll position is controlled and remembered only for the entire component page, not for the other scrollbars in your component.
  • The routing pattern here can only be history, because it uses the pushState() added by history. See my description in chapter 6.
const router = new VueRouter({
mode:'history'.// The default is hash moderoutes: [...] , scrollBehavior (to,from, savedPosition) {
     // to: to enter the target routing object, where to go. Same as the navigation guard beforeEach
	 //from: route object left, where to come
	 //savedPosition: record value when clicking forward/back {x:? ,y:? }. And will only be triggered if the browser moves forward or backward.
    {x: number, y: number} or {selector: string, offset? : {x: number, y: number}}, where the selector receives a string hash, such as '#foo', and you can set the offset by offset. The version must be greater than 2.6+
	// For example
	if(savePosition) { // If the browser is forward or backward, return to the previous saved location
      return savePosition;
    }else if(to.hash) {// If there is a hash, scroll to the hash location
      return {selector: to.hash}
    }else{
	  return {x:0.y:0}// Otherwise scroll to the top}}})Copy the code