introduce

Vue Router is the official route manager of vue.js.

Routing refers to the process of resolving addresses and obtaining resources.

basis

The installation

npm i -S vue-router
Copy the code

use

// main.js
// Import vue and vue-router
import Vue from 'vue';
import VueRouter from 'vue-router';
// Install the vue-router and call its install method
Vue.use(VueRouter);
// Import components
import Foo from '@/components/foo';
import Bar from '@/components/bar';
import Logs from '@/components/logs';
import NotFound from '@/components/not-found';
// Create a routing match table
const routes = [
  // Switches to component foo when matched to '/foo'
  { path: '/foo'.nama: 'Foo'.component: Foo },
  // When matched to '/bar', switch to component bar
  { path: '/bar'.nama: 'Bar'.component: Bar },
  // When '/logs/aaa/ BBB' is matched, switch to component logs,
  // User = 'aaa' and date = 'BBB'
  { path: '/logs/:user/:date'.name: 'Logs'.component: Logs },
  // Matches '/redirect', URL changes and navigates to '/foo'
  { path: '/redirect'.redirect: '/foo' },
  // Match to '/alias', same URL but navigate to '/foo'
  { path: '/alias'.alias: '/foo' },
  // Match all paths, because the later routes have lower priority, so it is often used to listen for 404
  { path: The '*'.nama: 'NotFound'.component: NotFound },
];
// Create a routing instance
const router = new VueRouter({ routes });
// Create a vue instance and bind the Router to it
const app = new Vue({
  router,
}).$mount('#app');
Copy the code
<template> <div id="app"> <router-link to="/foo">Route to Foo</router-link> <router-link to="/bar">Route to Bar</router-link> <a @click="routeToLogs('xiaoming', '2020-08-15')">Route to Logs</a> <router-view /> </div> </template> <script> export default { watch: $route(to, from) {console.log(to.params); // Route parameter console.log(to.query); RouteToLogs (user, date) {this.$route. push({name: 'Logs', params: { user, date, }, query: {}, }); ,}}}; </script>Copy the code

The advanced

Programmatic navigation

const router = this.$router;
// push: navigate to the specified path and add the navigation record
router.push('/user');
router.push({
  name: 'User'.params: { userId: '123' },
  query: { plan: 'private' },
  onComplete() {},
  onAbort(){}});// replace: navigates to the specified path and replaces the current navigation record
router.replace({});
// go: the corresponding number of steps forward, negative number of steps back
router.go(2);
router.go(-1);
Copy the code

Navigation guard

Navigational guard methods typically take three arguments:

  • to: Indicates the current matched route.
  • from: Indicates the original route.
  • next: This method is called to “pass” the guard and jump successfully.
// router.js
new VueRouter({
  routes: [{// Route exclusive guard
      beforeEnter(to, from, next){},},],// Global guard
  beforeEach(to, from, next) {},
  beforeResolve(to, from, next) {},
  afterEach(to, from, next){}});// component.vue
export default {
  name: 'Component'.// Inside the component guard
  beforeRouteEnter(to, from, next) {},
  beforeRouteUpdate(to, from, next) {},
  beforeRouteLeave(to, from, next){}};Copy the code

Note that changes in route parameters and query parameters do not trigger the navigational guard.

Named view

// ComponentDefault, ComponentA and componentB,
// Each is rendered to 
      
        of the corresponding name
      
const routes = [
  {
    path: '/'.components: {
      default: ComponentDefault,
      viewA: ComponentA,
      viewB: ComponentB,
    },
  },
];
Copy the code
<div id="app">
  <! --name defaults to default-->
  <router-view />
  <router-view name="viewA" />
  <router-view name="viewB" />
</div>
Copy the code

Dynamic Route Matching

Get route parameters:

this.$router.params;
Copy the code

Routing component parameters:

const routes = [
  // Boolean mode: pass routing parameters to the props of the User
  { path: '/user/:id'.component: User, props: true },
  // Object mode: pass props to the User props
  { path: '/user/:id'.component: User, props: {}},// Function mode: Pass the return value of props to the props of User
  { path: '/user/:id'.component: User, props(route){}},];Copy the code

Nested routines by matching

// Matches '/user/:id/profile',
// The component User is rendered to 
      
        in the component App,
      
// The component UserProfile will be selected to wrap around the component User's 
      
const routes = [
  {
    path: '/user/:id'.component: User,
    children: [{path: 'profile'.component: UserProfile,
      },
      {
        path: 'posts'.component: UserPosts,
      },
    ],
  },
];
Copy the code
<! --App.vue-->
<div id="app">
  <router-view />
</div>

<! --User.vue-->
<div id="user">
  <h2>UserID: {{ $route.params.id }}</h2>
  <router-view />
</div>
Copy the code

Routing named

const route = {
  name: 'foo'};this.$router.push({
  name: 'foo'});Copy the code

Routing meta information

const route = {
  meta: {
    requireAuth: true.requireLog: true,}};Copy the code

Route rolling behavior

// savedPosition is the scrollbar position (only available for forward/backward)
new VueRouter({
  scrollBehavior(to, from, savedPosition) {
    // Return to the scroll position
    return {
      x: 0.y: 32}; }});Copy the code

Route transition dynamic effect

See this article for details.

<! --App.vue-->
<transition>
  <router-view></router-view>
</transition>
Copy the code

Route lazy loading

Method 1: Use Vue asynchronous components:

const route = {
  path: '/'.component: () = >
    Promise.resolve({
      // The component defines the object})};Copy the code

Method 2: use import syntax:

const route = {
  path: '/'.component: () = > import('@/components/component-name'),};Copy the code

API

router

/ / configuration items
const router = new VueRouter({
  mode,
  base,
  routes,
  linkActiveClass,
  linkExactActiveClass,
  parseQuery,
  stringifyQuery, // Custom parse/antiparse functions
  scrollBehavior,
});

// Instance properties and methods
router.app; // Mount the Vue root instance
router.mode;
router.currentRoute; // The current routing information object
router.beforeEach();
router.beforeResolve();
router.afterEach();
router.push();
router.replace();
router.forward();
router.back();
router.getMatchedComponents(); // Returns an array of components matching the current route
router.addRoutes(routes); // Add routing rules
router.onReady(callback);
router.onError(callback);

// In the component, access the router through this.$router
this.$router;
Copy the code

route

/ / configuration items
const route = {
  path,
  name,
  meta,
  redirect,
  alias,
  children,
  component,
  components,
  props,
  beforeEnter,
  caseSensitive, // Is case sensitive
};

// Instance properties
route.path; // Routing path
route.fullPath; // Full path
route.hash; // Hash value of the route
route.params;
route.query;
route.name; / / routing
route.redirectedFrom; // Redirect the source route

// In the component, access the currently matched route through this.$route
this.$route;
Copy the code

// props
to, replace, append // Pass path or route
tag // The type of tag to render
active-class.exact-active-class// Activate the styleexact// Whether the match is exact, the default is to include match (/a/bIt also matches PI over PIa)event// The event that triggers the navigation, default isclick
Copy the code

name; / / the view name
Copy the code

reference

  • Vue Router official document