One: Know routes and routing rules

With the advent of Ajax, there was a development pattern of front – and back-end separation.

The back end only provides apis to return the data, the front end gets the data through Ajax and can render the data to the page through JavaScript,

The biggest advantage of this approach is the clarity of responsibility on the front and back ends, with the back end focused on data and the front end focused on interaction and visualization.

Then the front-end routing was born on the basis of the back-end routing.

It’s important to know url hashes and HTML5 history in advance

Vue-router is an official routing plug-in of vue.js. It is deeply integrated with vue.js and suitable for building single-page applications. Its official website: router.vuejs.org/zh/

Vue-router is based on routes and components

  • Routing is used to set access paths and map paths to components.
  • In a vue-Router single-page application, a change in the path of the page is a component switch

Two: Install and configure vue-Router

Common installation methods of VUe-Router include CDN, NPM, and VUE CLI (it is preferred to learn NPM to be familiar with Webpack)

  1. Installation:

    For example, NPM install vue-router –save or vue UI visual plug-in in the new Vue CLI

    The installation will appear in the configuration file dependency description

    (NPM is also available when filling in dependency)

  2. Configuration:

    Applying project structure in modular engineering:

    • Import the routing object and call vue. use(vue-router)

    • Create a routing instance and pass in the routing mapping configuration

    • Mount the route instance created in the VUE example

      //router/index.js
      import Vue from 'vue'
      // Configure routing information
      import VueRouter from 'vue-router'
      // Install the plug-in through vue. use(plug-in)
      Vue.use(VueRouter)
      // Configure the mapping
      const routes = []
      Create the VueRouter object
      const router = new VueRouter({
        //es6 enhancement
        routes
      })
      // Import it from main.js and mount it
      export default router
      Copy the code
      //main.js
      // Import router automatic search /index.js
      import router from './router'
      new Vue({
        router,  // Mount add route
        render: h= > h(App)
      }).$mount('#app')
      Copy the code

Three: Use vue-router

  • Creating a Routing Component
  • Configuring route mapping: Component and path mapping
  • Reason for use: Pass<router-link>and<router-view>
//router/index.js
// Configure the mapping
const routes = [
/ / case:
  {
    path: '/test'.name: 'test'.component: testView
  },
]
Copy the code
//components/test.vue //component contents <template > <div class="a"> I am the test component </div> </template> <script> // around test component export default { name: "test", }; </script> <style scoped> .a { width: 100px; height: 100px; background-color: red; } </style>Copy the code
// App. vue component contents hang <template> <div id="app"> <router-link to="test"></router-link> <router-view></router-view> </div> </template>Copy the code

After starting the service, routing can be used for access:

4. Change the default route value to the history mode

Route Default value

How can I make the path jump to the home page by default and

render the home page component?

You only need to configure one more mapping as shown in the following figure:

//index.js
// Configure the mapping
const routes = [
  {
    path:'/'.redirect:'/default'
    // Redirect to /default if the default path is /},]Copy the code

Example:

//views/default.vue <template> <div> <h2> default </h2> </div> </template> <script> export default {name: 'defaultView', components: { } } </script> <style> h2{ color: pink; font-size: 100px; } </style>Copy the code
//router/index.js
import Vue from 'vue'
// Configure routing information
import VueRouter from 'vue-router'
import testView from '.. /views/testView.vue'
import defaultView from '.. /views/default.vue'
// Install the plug-in through vue. use(plug-in)
Vue.use(VueRouter)
// Configure the mapping
const routes = [
  {
    path:'/'.redirect:'/default'
    // Redirect to /default if the default path is /
  },
  {
    path:'/test'.name:'test'.component:testView
  },
  {
    path:'/default'.name:'default'.component:defaultView
  }
]

Create the VueRouter object
const router = new VueRouter({
  //es6 enhancement
  routes
})

// Import it from main.js and mount it
export default router

Copy the code
//App.vue <template> <div id="app"> <div> <router-link to="test">testView</router-link> <router-link </router-link> <router-view></router-view> </div> </div> </template>Copy the code

Effect:

The history mode

There are two ways to change your path:Copy the code
  • The URL hash

  • It’s history

    By default, path changes use the HASH of the URL.

    Using HTML5’s History mode, it’s very easy to configure as follows:

const router = new VueRouter({
  //es6 enhancement
  routes,
  mode:'history'
})
Copy the code

Sample renderings:

You can see the hash # is gone

Five: Router-link supplement

Other attributes:

  • tag: Tag can be specified<router-link>Which components will be rendered, such as the code above<li>Element, rather than<a>
  • Replace: Replace does not leave a history, so if you specify replace, the back key will not return to the previous page
  • active-class: when<router-link>When the route matches successfully, the system automatically sets a router-link-active class for the current element. You can change the default name of the router-link-active class. This class is used when performing highlighted navigation menus or tabbars at the bottom. The default router-link-active is used instead of modifying the class attributes.

Example:

<template> <div id="app"> <div> <router-link to="test" tag="button" replace >testView</router-link> <router-link To ="default" tag="li">default home </router-link> <router-link to="test" tag="button" replace active-class="active">testView222</router-link> <router-view></router-view> </div> </div> </template> <style> .active{ background-color:red; } .router-link-active{ color: blue; } </style>Copy the code

Effect:

Modify linkActiveClass

The effect can also be shown

Six, routing code jump

Sometimes, a page jump may require the execution of the corresponding JavaScript code. In this case, we can use the second jump method. For example, we can modify the code as follows:

Effect:

Dynamic routing

In some cases, the path path of a page may be indeterminate. For example, when we enter the user interface, we want the following path:

  • / user/aaaa or/user/BBBB
  • In addition to the previous /user, the user ID is followed
  • This path/Component matching is called dynamic routing (which is also a way of routing data).

Effect:

! [1](gitee.com/wx_7585a018… (1).gif)

8. Route lazy loading

Method 1: combine Vue asynchronous components and Webpack code analysis.

const Home = resolve= > { require.ensure(['.. /components/Home.vue'].() = > { resolve(require('.. /components/Home.vue'))})};Copy the code

Mode 2: WRITTEN by AMD

const About = resolve= > require(['.. /components/About.vue'], resolve);
Copy the code

Approach 3 (key): In ES6, we can write a much simpler way to organize code splitting between Vue asynchronous components and Webpack.

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

Nine, set by

Nesting is a very common feature

There are two steps to implement nested routines:

  1. Create the corresponding child components and configure the corresponding child routes in the routing map.

  2. Use the

    tag inside the component.

Effect:

X. Parameter transfer

The way parameters are passed

Preparations:

To demonstrate passing parameters, let’s create one more component here and configure it

  • Step 1: Create a new component, profile.vue
  • Step 2: Configure route mapping
  • Step 3: Add the jump<router-link>

There are two main types of passing parameters: Params and Query

  • Types of params:
    • Set the route format to /router/: ID
    • How it is passed: Follow path with the corresponding value
    • The path is /router/123, /router/ ABC
  • The type of query:
    • The route format is /router, which is the common configuration
    • Pass method: The object uses the Query key as the pass method
    • Route: /router? id=123, /router? id=abc
Parameter transfer mode 1:<router-link>
//porfile.vue <template> <div> <h2> <h3>userId:{{$route.params.userid}}</h3> <h3>age:{{$route.params.userid}}</h3> <h3>age:{{$route.params.userid}} $route.query.age }}</h3> <h3>size:{{ $route.query.size }}</h3> </div> </template> <script> export default { name: "profile", components:{ } }; </script> <style scoped> h2{ color: rgb(90, 184, 140); font-size: 100px; } </style>Copy the code
/ / router/index. Js added
const profile = () = > import('.. /views/profile.vue')
  {
    path:'/profile/:userId'.component:profile
  }
Copy the code
//App.vue
<template>
  <div id="app">
    <div>
      <router-link to="/default">default</router-link>
      <div></div>
      <router-link to="/Home">Home</router-link>
      <div></div>
      <router-link :to="/profile/+userId">profile(params)</router-link>
      <div></div>
      <router-link :to="{
        path:'/profile/'+userID,
        query:{age:20,size:18}
      }">porfile(query)</router-link>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      userId:234
    }
  },
}
</script>
<style>
</style>

Copy the code

Renderings:! [Route Parameter Passing (1)](gitee.com/wx_7585a018… (1).gif)

The second way to pass parameters: JavaScript code
//App.vue
<template>
  <div id="app">
    <div>
      <button>default</button>
      <button @click="toHome">Home</button>
      <button @click="toprofile">profile</button>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      userId:234
    }
  },
  methods: {
    toHome(){
      this.$router.push('/Home/'+this.userId)
    },
    toprofile(){
      this.$router.push({
        path:'/profile/'+this.userId,
        query:{age:20,size:18}
      })
    }
  },
}
</script>

<style>
</style>

Copy the code

To obtain parameters

The parameter is obtained from the $route object.

In applications that use vue-Router, the route object is injected into each component with a value of this.$route and updated when the route is switched.


r o u t e and The route and
A router is different

  • Router is an instance of VueRouter. If you want to navigate to different urls, you use router as instance VueRouter. If you want to navigate to different urls, you use router.push
  • $route indicates the current router jump object, which can obtain name, path, query, and params

11. Navigation guard

Navigation guard is mainly used to guard navigation by jumping or canceling.

There are several opportunities for embedding route navigation: global, single route proprietary, or component level.

(Remember that changes to parameters or queries do not trigger entry/exit navigational guards. You can cope with these changes by observing the $route object, or using the beforeRouteUpdate component internal guard.)

  • Vue-router provides a navigational guard that listens for incoming and outgoing routes.
  • Vue – the router providesbeforeEachandafterEachHook functions that fire before and after the route is about to change.

BeforeEach function:

Example:

BeforeEach to modify headings as an example.

  • Define some titles in the hooks, which can be defined using meta data
  • Second, using the navigation guard, change our title
    • Three parameters of the navigation hook:
    • to: Routing object of the destination to be entered.
    • from: Current navigation route object to leave.
    • next: Calls this method before going to the next hook.
//router/index.js
 {
    path:'/default'.name:'default'.component:defaultView,
    meta: {title:'default'}}, {path:'/profile/:userId'.component:profile,
    meta: {title:'profile'
    }
  }
router.beforeEach((to,from,next) = > {
  // Jump from from to to
  document.title = to.matched[0].meta.title
  console.log(to);
  next()
} )
Copy the code

Effect:

! [Navigation Guard (1)](gitee.com/wx_7585a018… (1).gif)

Additional questions:

BeforeEach in the variable from defines an unreferenced eALint code check error resolution:

// package.json
rules: {
    "no-unused-vars":"off"
}
Copy the code

Supplement:

  1. If it is a post-hook, that is, afterEach, you do not actively call the next() function.
  2. Supplement 2: The navigation guard we used above is calledGlobal guard.
    • Route exclusive guard
    • Guards within components

For details, please refer to the official website of Vue Router to update data

Twelve, keep alive

  • Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.
    • They have two very important properties:
    • Include-string or regular expression. Only matching components are cached
    • Exclude – a string or regular expression. Any matching component will not be cached
  • Router-view is also a component. If the router-view is wrapped directly in keep-alive, all view components matched by the path will be cached:
  • Verify this by declaring a periodic function by create
//App.vue <keep-alive> <router-view> <! </router-view> </keep-alive>Copy the code

Attached: Vue-Router knowledge quantization map