What is vue-router? Why don’t we just write links with the A tag like before? How to use it? What are common routing operations?

What is a Vue Router

Vue Router is the official route manager of vue.js. Its deep integration with vue.js core makes building single-page applications a breeze. The features included are:

  • Nested routing/view chart
  • Modular, component-based routing configuration
  • Route parameters, queries, and wildcards
  • View transition effect based on vue. js transition system
  • Fine-grained navigation control
  • Links with automatically activated CSS classes
  • HTML5 historical mode or Hash mode is automatically degraded in IE9
  • Custom scroll bar behavior
Note:
routeThis is all the routing information for the current page,
routerIs a method of routing.

router-link

<router-link to=" XXX "tag=" "> // Router-link to=" XXX" tag=" "> <router-link to=" XXX "tag=" "Copy the code

Router-link-exact-active: indicates that the routes match completely. Currently, router-link-active indicates that the routes do not match completely. To: indicates the link of the destination route. When clicked, the internal value of to is immediately passed to router.push(), so this value can be a string or an object describing the destination location.

<! - string - > < the router - link to = "home" > home < / router - the link > <! <a href="home"> home </a> <! <router-link V-bind :to="'home' > home </router-link> <! <router-link :to="'home' > home </router-link> <! -- -- ditto -- -- > < the router - link: to = "{path: 'home'}" > home < / router - the link > <! --> <router-link :to="{name: 'user', params: {userId: 123}}"> user </router-link> <! /register? plan=private --> <router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>Copy the code

Programmatic navigation

Instead of using the router-link tag to create an A tag to define navigation links, we can use the router instance method to write code to do so. This.$router.push(): Arguments in parentheses are the same as to methods

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
  • Note: Params is ignored if path is provided, which is not the case with Query in the above example. Instead, in the following example, you need to provide either the route’s name or a handwritten path with arguments:

    const userId = ‘123’ router.push({ name: ‘user’, params: { userId }}) // -> /user/123 router.push({ path: Router.push ({path: ‘/user’, params: {userId}}) // -> /user

Dynamic routing and nested routines

Dynamic routing: a “path parameter” is marked with a colon:. When a route is matched, the parameter value is set to this.$route.params

Note: Child path does not write a slash

import Home from '.. /views/Home' import Products from '.. /views/Products' import Category from '.. /views/Category' export default [ { path: '/home', name: 'home', component: Home }, { path: '/Products', name: 'products', Component: products, children: [{path: ':cateName',// path not slash name: 'category', Component: Category }] } ]Copy the code

router-view

The children router-view is configured in the parent component

Named view

Sometimes you want to show multiple views at the same time (sibling) rather than nested, such as creating a layout that has sidebar (side navigation) and main (main content) views. Instead of having a single exit, you can have multiple individually named views in the interface. If router-view does not have a name, it defaults to default

<template> <div id="app"> <h2> header </h2> <div class="main">< /router-view></div> <router-view name="x-footer"></router-view> </div> </template> export default [ { path: '/home', name: 'home', components: Default: Home, 'x-footer': footer}} {// Components, default means no unnamed component (in this case app.vue) default: Home, 'x-footer': footer}}Copy the code

Capture all routes or 404 Not found routes

Regular arguments only match characters in URL fragments delimited by /. If we want to match any path, we can use the wildcard (*) :

{/ / will match all path path: '*'} {/ / will match with ` / user - ` path at the beginning of arbitrary path: '/ user - *}Copy the code

Redirect and alias

Note: routes containing wildcards should be placed last

Export default [{// redirect from "/" to "/home" so that the root path becomes home path: '/', redirect: '/home'}]Copy the code

Navigation guard (often used for permission verification)

Vue-router provides navigation guards that are used to guard navigation by jumping or canceling

Global front-guard -beforeEach

The global navigation guard can be done in main.js because it needs to be done on the router instance for global permission authentication

  const router = new VueRouter({ ... })
  router.beforeEach((to, from, next) => {
    next()
  })
Copy the code

To: which component to go to, from: which component to come from next: The next() method must be called otherwise the route cannot jump access

  • Use meta when adding extended parameters to a route in addition to its own parameters

Guards within components

const Foo = { template: `... ', beforeRouteEnter (to, from, next) {// Call the render component before the corresponding route is confirmed // no! Can!!!! }, beforeRouteUpdate (to, from, next) {// When the current route changes, For example, for a path /foo/:id with dynamic parameters, // will be reused since the same foo component will be rendered when it jumps between /foo/1 and /foo/2. And the hook will be called in that case. // Call beforeRouteLeave (to, from, next) {// Call beforeRouteLeave (to, from, next) {Copy the code

BeforeRouteUpdate: This is where ajax requests can be sent before routing updates. BeforeRouteEnter is usually used first when using beforeRouteUpdate. Instead of getting this in beforeRouteEnter, you can pass in next a callback whose first parameter, VM, is this, and beforeRouteEnter is only executed once on the first entry.

Before, there was no beforeRouteUpdate. Instead, watch can watch this. Everything on

Route lazy loading

Components corresponding to different routes are divided into different code blocks, and then the corresponding components are loaded when the route is accessed, and the promise is returned using import to load asynchronously

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

Package the code for all three components into a SINGLE JS file.

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

Native uses this to bind an event to the root DOM element of the current component when no event is available