Most of this article is from the official website, a summary of the use of the official website.

The basic use

There are still a few steps to set up the use of the route, I guess many partners and I, not to sum up may really remember ah. The methods of use are divided into Html and Javascript.

HTML

   <div id="app">
        <h1>Hello App</h1>
        <! -- Use the router-link component to navigate.
        <! -- Specifies the link by passing in the 'to' attribute.
        <! -- <router-link> will be rendered as a '<a>' tag by default.
        <router-link to="/foo/panhe">Go to Foo</router-link>
        <router-link to="/bar">Go to Bar</router-link>

        <! -- Route exit -->
        <! -- Routing matching components will be rendered here -->
        <router-view></router-view>
    </div>
Copy the code

The outermost div with id=’app’ is the container for the vue instance to mount, needless to say. Two things were done internally:

  • Define navigation components. Use the

    component exposed by the Vue-Router component library to define the navigation tag, with the to attribute specifying the link to jump to. Router-link is eventually compiled into
    tags.
  • Define the render location. Use the

    component exposed by the Vue-Router component to control the rendering position. When the browser’s behavior matches one of our routing lists, it renders the component in router-view.

Javascript

// 1. Define (routing) components. const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } // 2. Define routes // Each route should map one component. Where "component" can be a component constructor created by // vue.extend (), // or just a component configuration object. const routes= [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar }, ] // 3. Const router = new VueRouter({routes}) // 4. Create and mount the root instance. const app = new Vue({ router }).$mount('#app')Copy the code

The js part does four things:

  1. Define the component that matches the route
  2. Define the route list. Each route corresponds to a rendered component.
  3. Create a router instance with VueRouter. The route list in the second step is used as the parameter
  4. Create a VUE instance and mount the Router object


Dynamic routing

Dynamic routing is used when all routes of a template are mapped to the same component. Dynamic routing is also a way for components to pass parameters. Here’s how he uses it:

const User = { template: '<div>User {{$route.params.id}}</div>' } const router = new VueRouter({ routes: [// Dynamic path parameters start with a colon {path: '/user/:id', Component: user}]})Copy the code

A “path parameter” uses the colon: notation. When a route is matched, the parameter value is set to this.$route.params, which can be used within each component. In addition to $route.params, the $route object provides additional information. For example, $route.query(the URL has query parameters). In this case, the component updates corresponding to route changes are special. For details about route changes, click here

Embedded routines by

Any application that is slightly larger is going to have nested routines. The building Lord borrow set routine origin to say the majority of the front-end architecture that has seen at present. There will be an app. vue file, but most of the time this file just provides the outermost layer of router-view, as shown below

App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
    }
  },
  components: {
  },
  methods: {
  }
}
</script>
<style lang="less">
</style>
Copy the code

router.js

import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ mode:'history', base: publicPath, routes: [ { path:'/', redirect:'/home', component:index, name:'index', children:[{ path:'/', redirect:'/home', component:home, Name: 'home'}}, {path: '/ login' component: login, name: 'login', meta: {title: 'login'}}]})Copy the code

In router.js, routes matching name:’ index’ and/or name:’login’ are rendered to app.vue. Of course, all the routes at the same level correspond to the router-view of app. vue. At this point, the main layout is written in Component: home, and the home component looks something like this.

<template>
    <div>
      <el-container>
      	<el-header calss="el-header"></el-header>
        <el-container>
           <menu></menu>
            <el-main>
              <div class="tags"></div>
              <el-dropdown></el-dropdown>
              <el-scrollbar>
                  <router-view></router-view>
	       </el-scrollbar>
            </el-main>
        </el-container>
      </el-container>
    </div>
</template>
<script type="text/javascript">
export default {
    components: {},
    data: funtion() {},
    methods: {},
    computed: {},
    watch: {}
}
</script>
<style type="text/css" lang="less"></style>
Copy the code

As you can see, inside the Home component, we can customize the header component and the menu bar component (permissions can be done here), and then finally we have a router-View component that renders the children of the Home, which is where nesting occurs. Business routes are written in the home child. Most of the current front-end architecture is similar to this idea, whether it is VUE or React.

Programmatic navigation

This.$router object provides a series of methods to jump to a page. The router object’s methods are summarized as follows:

push

Router.push ('home') // Object router.push({path: 'home'}) // Named route Router.push ({name: 'user', params: {userId: '123'}}) // change to /register? plan=private router.push({ path: 'register', query: { plan: 'private' }})Copy the code

Router.repalce is similar to router.push, except that it does not add a new record to history, but the same method name

go

Forward () router.go(1) Router.go (-100) router.go(100) router.go(100)Copy the code

Router. Push, the router. The router and replace. Go to the window. The history. The pushState, window. History. ReplaceState and window history. Go like, In fact, they do emulate the Window.history API

So, more basic functions to see the official website, and then introduce some advanced methods.

The advanced

Navigation guard

A navigational guard is a set of routing hook functions that are triggered to handle different things at the same time. There are three types of navigation guards:

  1. global
  2. single-routed
  3. component-level
Global guard
  1. router.beforeEach
  2. router.beforeResolve
  3. router.aftereEach
Route exclusive guard
  1. beforeEnter
Guards within components
  1. beforeRouteEnter
  2. beforeRouteUpdate
  3. beforeRouteLeave
Complete navigation parsing process
  1. Navigation is triggered.
  2. Call the beforeRouteLeave guard in the deactivated component.
  3. Call the global beforeEach guard.
  4. Call the beforeRouteUpdate guard (2.2+) in the reused component.
  5. Call beforeEnter in routing configuration.
  6. Parse the asynchronous routing component.
  7. Call beforeRouteEnter in the activated component.
  8. Call the global beforeResolve guard (2.5+).
  9. Navigation confirmed.
  10. Call the global afterEach hook.
  11. Trigger a DOM update.
  12. Call the callback passed to Next in the beforeRouteEnter guard, and the created component instance is passed in as an argument to the callback.

Routing meta information

Routing meta information refers to meta information in a routing object. This is where you can set some permissions or other information. I’ve already touched on the need to display a proxy number on each left sidebar, so setting which routes to display will be set in these meta’s. Other types of requirements will do. The meta information can be obtained by using the following methods:

router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (! auth.loggedIn()) { next({ path: '/login', query: { redirect: To.fullpath}})} else {next()}} else {next() // Make sure to call next()}})Copy the code

Route lazy loading

Routing lazy setup is simple, just change the imported component to the following form:

const Foo = () => import('./Foo.vue
Copy the code

Nothing else needs to change. This is achieved with a combination of vUE asynchronous components and webpack cutting capabilities

Note: If you are using Babel, you will need to add the syntax-dynamic-import plug-in so that Babel can parse the syntax correctly.

Conclusion: This is a general summary of the use of vue-Router. Next, I’ll examine the source code starting with basic usage.