The use of VueRouter

Vue-router installation and configuration

First, for a project, we need unified management of the VueRouter sub-files. In general, we will create a router folder in the SRC directory of the project. In the Router folder, we will create two base files, index.js and router.js.

- src-router index.js // Stores the basic router configuration router.js // Stores the routes informationCopy the code
// Basic configuration of index.js on the router
import Vue from 'vue' // The Vue object is introduced to facilitate the registration of VueRouter
import VueRouter from 'vue-router' // Add a VueRouter to create a new object
import routes from './router' // routes is the information we use to configure the route

Vue.use(VueRouter) // Register the route

const router = new VueRouter({
  routes  // Add the routing configuration information of routes to the created routing object
})

export default router // Export the Router object, which is assigned to the vue instance in main.js
Copy the code
// Basic router.js configuration information under router
const Home = () = > import('@/views/Home') // Route lazy loading
const About = () = > import('@/views/About') // Route lazy loading
const routes = [
  {
    path: '/'.name: 'Home'.component: Home
  },
  {
    path: '/about'.name: 'About'.component: About
  }
]
export default routes // Export the routes object in index.js

Copy the code

The vue-router route was loaded lazily. Procedure

The purpose of route lazy loading is to reduce the time required to enter the page for the first time and enable users to view the home page more quickly.

Route lazy loading will divide the packed JS file into several small JS files according to your Settings, and load the JS file according to the needs of the route jump to the route address, which address will be loaded.

// How to use lazy route loading
// router.js file
const Home = () = > import('@/views/Home') // Route lazy loading
const About = () = > import('@/views/About') // Route lazy loading
const routes = [
  {
    path: '/'.name: 'Home'.component: Home
  },
  {
    path: '/about'.name: 'About'.component: About
  }
]
export default routes // Export the routes object in index.js
Copy the code

The nested routine of vue-router is defined by

Nested routing is the ability to continue routing within a routed page. Nested means routing within routing.

For example, in Vue, if we do not use nested routines, we only have a

, but if we use a

in a component, which constitutes nesting.

/ / router. Js file
const Home = () = > import('@/views/Home') // Route lazy loading
const About = () = > import('@/views/About')
const Parent = () = > import('@/views/Parent')
const Child = () = > import('@/views/Child')
const routes = [
  {
    path: '/'.name: 'Home'.component: Home
  },
  {
    path: '/about'.name: 'About'.component: About
  },
// The path of children must not be followed by a /, otherwise it will be resolved as a root route
  { 
    path: '/parent'.name: 'Parent'.component: Parent,
    children: [{path: 'child'.component: Child
      }
    ]
  }
]
export default routes
Copy the code

Vue-router Indicates the named route

To assign a unique name to a route, which is used in the

tag. You can use the to attribute of the tag to jump to the specified named route. Named routes can also be used in the subsequent routing daemon, redirection, etc.

/ / router. Js file
const Home = () = > import('@/views/Home') // Route lazy loading
const About = () = > import('@/views/About')
const Parent = () = > import('@/views/Parent')
const Child = () = > import('@/views/Child')
const routes = [
  {
    path: '/'.name: 'Home'.// This is called named routing
    component: Home
  },
  {
    path: '/about'.name: 'About'.component: About
  },
// The path of children must not be followed by a /, otherwise it will be resolved as a root route
  { 
    path: '/parent'.name: 'Parent'.component: Parent,
    children: [{path: 'child'.name: 'child'.component: Child
      }
    ]
  }
]
export default routes
Copy the code
// In the parent. Vue file // with the router-link to attribute and the v-bind binding, we can name the route, <template> <div> this is parent <router-link :to="{name: 'child'}">child</router-link> <router-view></router-view> </div> </template>Copy the code

Vue-router Naming view

A named view is usually used when multiple routing views are required. For example, a VUE page needs to display three different < router-views >. In this case, the named view must be used to achieve the effect

/ / router. Js file
const Home = () = > import('@/views/Home')
const About = () = > import('@/views/About')
const Parent = () = > import('@/views/Parent')
const Header = () = > import('@/views/Header')
const Right = () = > import('@/views/Right')
const Left = () = > import('@/views/Left')

const routes = [
  {
    path: '/'.name: 'home'.component: Home
  },
  {
    path: '/about'.name: 'About'.component: About
  },
// Implement the named view through the children child route in the parent page
  {
    path: '/parent'.name: 'Parent'.component: Parent,
    children: [{path: ' '.components: {
          default: Header,
          left: Left,
          right: Right
        }
      }
    ]
  }
]
export default routes
Copy the code
// In parent-vue <template> <div> this is parent <router-view></router-view> <router-view name="left"></router-view> <router-view name="right"></router-view> </div> </template>Copy the code

Vue – the Router redirects

Redirection is a redirection of the current routing function. For example, we can redirect/to /home to prevent users from manually accessing/and keep the destination address of the two routes consistent

/ / router. Js file
const Home = () = > import('@/views/Home')
const About = () = > import('@/views/About')
const Parent = () = > import('@/views/Parent')
const Header = () = > import('@/views/Header')
const Right = () = > import('@/views/Right')
const Left = () = > import('@/views/Left')

const routes = [
  {
    path: '/home'.name: 'Home'.component: Home
  },
// All three methods provide redirect redirection. Redirect prevents users from accessing the url path directly by modifying the url path
  {
    path: '/'.// redirect: { name: 'Home' }
    // redirect: '/home'
    redirect: to= > {
      return { name: 'Home'}}}, {path: '/about'.name: 'About'.component: About,
    redirect: to= > {
      return { name: 'Home'}}}]export default routes
Copy the code

Vue – the Router alias

Alias a route to make it easier to access the route, without being limited to the complex route nested address, an alias can replace the long address, more convenient to use.

/ / router. Js file
const Home = () = > import('@/views/Home')
const About = () = > import('@/views/About')
const Parent = () = > import('@/views/Parent')
const Header = () = > import('@/views/Header')
const Right = () = > import('@/views/Right')
const Left = () = > import('@/views/Left')
// The alias here is an alias. If the path has a long path length, the alias will look cleaner
const routes = [
  {
    path: '/home'.name: 'Home'.component: Home,
    alias: '/winter'}]export default routes
Copy the code

Programmatic navigation of vue-Router

In. Vue, users may need to manually jump to the page by connecting to it. At this time, programmatic navigation is needed to realize manual page jump, where push is to jump to the specified path, back is to return to the previous path,forward is to advance to the path before returning,replace is to replace the current path, Note that replace does not leave a jump record and therefore cannot be returned by back or forward, while push does.

// Programmatic navigation
<template>
  <div>
      this is parent
      <button @click="handleClick('push')">Jump to home page</button>
      <button @click="handleClick('back')">back</button>
      <button @click="handleClick('forward')">forward</button>
      <button @click="handleClick('replace')">Replace the current path</button>
  </div>
</template>
<script>
export default {
  name: 'Parent'.methods: {
    handleClick (type) {
      switch (type) {
        case 'push' :
          this.$router.push('/')
          break
        case 'back' :
          this.$router.back()
          break
        case 'forward':
          this.$router.forward()
          break
        case 'replace':
          this.$router.replace('/about')
          break
        default:
          break}}}}</script>
Copy the code

Programmatic navigation we can pass params or query to the destination route, and when we pass query, we’ll put? At the end of the URL. $thisisQuery $thisisQuery $thisisQuery $thisisQuery $thisisQuery $thisisquery $thisisquery If you are passing params, it is important to note that path and params cannot be used together. Path will cause params to fail. Params can be obtained from $route.params.name

// 传query
<script>
export default {
  name: 'Home'.methods: {
    handleClick () {
      console.log(this.$route)
      this.$router.push({
        // name: 'Home'
        path: '/home'.query: {
          name: 'thisisquery'
        }
      })
    }
  }
}
</script>
/ / the params
// Params cannot be used with path. Path causes params to fail
<script>
export default {
  name: 'Home'.methods: {
    handleClick () {
      console.log(this.$route)
      this.$router.push({
        name: 'Home'.params: {
          name: 'woshilisi'}})}}}</script>
Copy the code

Vue-router component parameters are transmitted

You can also use the props parameter of a component to pass routes, as long as you set the props: true attribute on the component to accept the parameters of the route. There are two other ways to set routes, namely, object mode and function mode.

// Routing props in three ways
// Boolean mode
// Router.js in the route configuration file
// Note that path is followed by the attribute name
  {
    path: '/about/:name'.name: 'About'.component: About,
    props: true
  }

// Object mode Note that the object mode path does not contain :name
  {
    path: '/about'.name: 'About'.component: About,
    // props: true
    props: {
      name: 'morenzhi'}}// Function mode Note that function mode has no path :name, and function mode can only pass values through query
  {
    path: '/about'.name: 'About'.component: About,
    props: (route) = > ({
      name: route.query.name
    })
  }

// In the.vue file
export default {
  name: 'About'.props: {
    name: {
      type: String.default () {
        return 'No value'}}}}Copy the code

Vue-router HTML5 History mode

History mode requires browser support. The default mode of VueRouter is hash, with # in the URL. In real projects, History mode is usually used, but it is important to note that History requires backend support because it is easy to get an error if the URL path does not match.

// Route index.js file
export default new Router({
		mode: 'history',
		routes
})
Copy the code

Vue-router Navigation guard

The navigational guard in VueRouter is essentially a hook function. It can perform a related operation when realizing the jump, such as navigation interception, redirection to the login page and so on. A total of seven functions related to the navigation guard are distributed in the route itself, inside a specific route, and inside the component.

// Navigation guard
/ / index. Js file
// to is the url of the invalid page
// from activates the page url
// next Performs the next step. If you do not call next, this page skip will not be performed. You must call next
router.beforeEach((to, from, next) = > {
  console.log('to:')
  console.log(to)
  console.log('from:')
  console.log(from)
  next()
})

// Back navigation hook
router.afterEach((to, from) = > {
  console.log('Rear navigation hook')})// Global parse guard
router.beforeResolve((to, from, next) = > {
  console.log('Global parse guard')
  next()
})

// Route exclusive guard
/ / the router. In js
  {
    path: '/about'.name: 'About'.component: About,
    props: (route) = > ({
      name: route.query.name
    }),
// Generally, you can determine the route from which the destination is coming, preventing users from manually entering the route address
    beforeEnter: (to, from, next) = > {
      console.log('Route Exclusive Guard')
      if (from.name === 'Home') {
        next()
      } else {
        next('/')}}}// The route guard within the component
// Note that inside beforeRouteEnter you cannot use this to get the current component object because the current component has not yet been rendered
<script>
export default {
  name: 'About'.props: {
    name: {
      type: String.default () {
        return 'No value'
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    console.log('Navigation guard within component')
    next(vm= > {
      console.log(vm.name)
    })
  },
// In general, beforeRouteLeave can be used to confirm the exit message. Next (false) can be used to cancel the current page jump
  beforeRouteLeave (to, from, next) {
    console.log('Leave navigation guard inside component')
    next()
	},
// The component is not destroyed and is entered when the current route is updated
  beforeRouteUpdate (to, from, next) {
    console.log('Update guard within component')
    next()
  }
}
</script>
Copy the code

Completed process:

1: Navigation is triggered

2: Call the leave guard beforeRouteLeave in the deactivated component

3: Calls the global front-guard beforeEach

4: Call beforeRouteUpdate in the reusable component

5: Calls the exclusive route guard beforeEnter

6: parses asynchronous routing components

7: Call beforeRouteEnter in the activated component

8: Call the global parse guard beforeResolve

9: Navigation is confirmed

10: Calls the global afterEach aftertick

11: DOM updates are triggered

12: Use the created instance to call the next callback inside the beforeRouterEnter guard

Vue-router Indicates the routing meta information

// Router.js file
{
    path:"/test".name:"test".component:() = >import("@/components/test"),
    meta: {title:"Test page"./ / configuration of the title
        keepAlive: true // Whether to cache}}// The code in index.js sets the title
router.beforeEach((to,from,next) = >{
    if(to.meta.title){
        document.title=to.meta.title } next() }) <! -- Code in app.vue --> <! -- route entry to be cached --><keep-alive>  
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive><! -- No need to cache the route entry --><router-view v-if=! "" $route.meta.keepAlive"></router-view>

Copy the code