Vue-router essentially adds a layer of front-end routing on the basis of the separation of the front and back ends.

The heart of front-end routing: Change the URL, but do not refresh the page as a whole.

URL hash and HTML5 history

When they change urls, they don’t refresh the entire page, only parts of it, and they don’t rerequest already-requested data.

The URL hash is the URL changed by the window’s Location API

location.hash = 'home'
Copy the code

Html5’s history mode, which is essentially a stack (last in, first out), pushes the name onto the stack via pushState.

history.pushState({}, ' '.'home')
// You can return the previous URL
history.back()
Copy the code

The replacement URL cannot be returned

history.replaceState({}, ' '.'home')
Copy the code

Move back

history.go(num)
num=-1 // return to the previous page
num=1  // Move forward one page
Copy the code

Vue-router Basic configurations

Install vue-Router first

NPM install vue-router or YARN add vue-routerCopy the code

Use vue-router in vUE to configure a simple route

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '.. /components/home/Home'
import About from '.. /components/about/About'

// Install vUE router in vUE
Use essentially calls the install method of vue-router and mounts it to vue. prototype
Vue.use(VueRouter)

// Configure the route here
const router = [
    {
        path: '/home'.component: Home
    },
    {
        path: '/about'.component: About
    }
]

const router = new VueRouter({
    // Configure the route
	router
})
Copy the code

Routing mode selection

There are three routing modes

  • Hash: The default routing pattern, with a hash character on the URL

  • History: Html5 routing mode, no # character

  • Abstract: The address of an abstract route does not change no matter how the route is redirected

const router = new VueRouter({
    router,
    // Select the routing mode
    mode: 'hash'
})
Copy the code

Route redirection

Keyword redirect: Navigate to a page when you log in for the first time

const router = [
    {
      	path: ' '.// 或者 path: '/'
        redirect: '/home'
    },
    {
        path: '/home'.component: Home
    },
    {
        path: '/about'.component: About
    }
]
Copy the code

Nested routing

The child route is stored mainly in the parent route through children

const router = [
    {
        path: '/home'.component: Home,
        children: [
            // Child routes can also use redirection
            {
                path: '/'.redirect: 'news'
            },
            {
                path: 'news'.component: News
            },
            {
                path: 'message'.component: Message
            }
        ]
    }
]
Copy the code

Route lazy loading

It can be used to load components only when they are used, or when they enter a route

Change how components are imported

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

Routing and the cords

There are two types of route parameters:

  • The params parameter is added directly after the route path, for example:http://www.localhost:3000/user/12
  • Query displays key-value pairs on the URL, passing objects such as:http://www.localhost:3000/user?name='zhangsan&age=18'

When using Params, dynamic routing parameters are required in the routing configuration

const router = [
    {
        path: '/home'.component: Home
    },
    {
        path: '/user/:id'.component: About
    }
]

// Use route to transmit parameters
/ / the declarative
<router-link to="/user/12"></router-link>
/ / programmatic
this.$router.push('/user/12')

// Get parameters
this.$route.params.id
Copy the code

Query, which passes the object parameters of the key-value pair schema without the need to configure dynamic parameters

// Use route to transmit parameters
/ / the declarative
<router-link :to="{path: '/user', query: {name: 'lisi', age: 18}}"></router-link>
/ / programmatic
this.$router.push({
    path: '/user'.query: {name: 'lisi'.age: 18}})// Get parameters
this.$route.query.name
Copy the code

The routing header

The title of the route is configured in the meta attribute of the route

const router = [
    {
        path: '/home'.component: Home,
        meta: {
            title: 'home'}}]/ / to get
this.$route.matched[0].meta.title
Copy the code

Route navigation guard

Before Global front guard

A step in the middle of a route jump

Pass three parameters:

  • To: indicates the target route object to be jumped to
  • From: indicates the route to leave
  • Next: indicates the route to be clicked. This parameter is mandatory

Next: Next () jumps to the next route by default, next(false) terminates the jump, and next(‘/’) jumps to a page.

Perform the render of title to the tag

router.beforeEach((to, from, next) = > {
    document.title = to.matched[0].meta.title
    next()
})
Copy the code

Vue-router is used globally

Declarative routing

Router-link is used for forward routes

The router-view command is displayed

Basic usage

<router-link to="/home" tag="button" replace active-class="active">Home</router-link>
<router-link to="/about" tag="button" active-class="active">About</router-link>
<router-link to="/user/123" tag="button" active-class="active">User</router-link>
<router-link :to="{path: '/profile', query: {name: 'lisi', age: 18}}" tag="button" active-class="active">Profile</router-link>
    
// Display the route
<router-view></router-view>
Copy the code

Key configurations in router-link:

  • To: indicates the route to be jumped
  • Tag: indicates the route representation. Button indicates the button
  • Replace: indicates a route that cannot be returned
  • Active-class: indicates the active state when a route is clicked

Programmatic routing

$router jump

Jump key mode

  • Push: returnable jump, stack structure, lifO
  • Replace: indicates that the route cannot be returned to the original route
  • Go (Param) : indicates the forward or backward route
  • Back: Returns the last route
  • Forward: Returns the previous route

The routing cache

keep-alive

use

<keep-alive exclude="Home">
	<router-view></router-view>    
</keep-alive>
Copy the code

When switching to another routing page, the route itself is cached (inactive components are cached) and will not be destroyed. This avoids repeated component creation and rendering and effectively improves system performance.

Exclude exclude cache