Vue front end road -- Vue Router

catalogue

1. Overview of Vue router

2. Installation and reference

3. Basic route usage

3.1. Primary routing

3.2. Dynamic routing parameter transmission (basic writing method)

3.3. Redirect route and 404 route

3.4. Nested Route

3.5. Declarative navigation and programmatic navigation

4. Named routes and named views

4.1. Named route

4.2. Named view

5. Dynamic routing parameter transmission (improved writing method)

6. Navigation guard

6.1. Global front guard

6.2. Global post hook

6.3. Route exclusive guard

7. Routing meta information

 

1. Overview of Vue router

Vue Router is the official route manager of vue. It is deeply integrated with the core of vue, making it easy to build page applications

2. Installation and reference

npm install vue-router

Use vue cli to build a vue project in main JS

import router from "./router";

// Create and mount root instances.
// Remember to inject routes through router configuration parameters,
// So that the whole application has routing function
new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

In router JS

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);
//Define route
// Each route should map a component. Where "component" can be
// Via Vue The component constructor created by extend(),
// Or, just a component configuration object.
// We'll talk about nested routing later.
export const routes = [];

// Create a router instance, and then pass it to 'routes' configuration
// You can also transfer other configuration parameters, but let's do it first.
const router = new VueRouter({
  routes
});
export default router;

3. Basic route usage

3.1. Primary routing

On app Configuration in Vue

<!-- Route exit -->
<!-- The components to which the route matches will be rendered here -->
<template>
  <div id="app">
    <router-view />
  </div>
</template>

In router JS

export const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("./views/login")
  },
]

3.2. Dynamic routing parameter transmission (basic writing method)

Scenario: it is often necessary to map all routes matched to a certain pattern to the same component, so we can use "dynamic segment" in the routing path of {Vue router} to achieve this effect.

export const routes = [
  // Dynamic path parameters start with a colon
  { 
    path: '/user/:id', 
    component: () => import("./views/user")
  }
]

Parameter values can be obtained through {{$route.params.id}}

When using routing parameters, such as navigating from / user/foo to / user/bar, the original component instances will be reused. Because both routes render the same component, reuse is more efficient than destroying and re creating. However, this also means that the component's lifecycle hook will no longer be called.

To respond to changes in routing parameters, you can simply watch (monitor changes) $route} object

watch: {
   $route(to, from) {
     // Responding to routing changes
   }
}

3.3. Redirect route and 404 route

The earlier a route is defined, the higher the priority.

export const routes = [
  { path: "", redirect: "/dashboard", hidden: true },
  { path: "/", redirect: "/dashboard", hidden: true },
  { path: "*", redirect: "/404", hidden: true }
]

The target of redirection can also be a named route:

{ path: '/a', redirect: { name: 'foo' }}

Even a method that dynamically returns the redirection target:

{ 
    path: '/a', 
    redirect: to => {
      // Method receives the destination route as a parameter
      // return redirected string path / path object
    }
}

3.4. Nested Route

Scenario: the actual application interface is usually composed of multi-layer nested components. Similarly, each dynamic path in the URL corresponds to each nested layer of components according to a certain structure, such as the horizontal main menu and the submenu under the left main menu

export const routes = [
  {
    path: "/dashboard",
    name: "Dashboard",
    redirect: "/dashboard/devops",
    component: () => import("./views/dashboard"),
    children: [
      {
        path: "devops",
        name: "Devops",
        component: () => import("./views/dashboard/devops"),
      },
      {
        path: "system",
        name: "System",
        component: () => import("./views/dashboard/system"),
      },
    ],
  }
]

Don't forget to create the render location of the route exit

<div id="app">
  <router-view></router-view>
</div>

3.5. Declarative navigation and programmatic navigation

Inside the Vue instance, you can access the routing instance through $router +. So you can call this$ router. push

Declarative:

<router-link 
  :to="{path:item.url}"
  v-for="(item, index) in navsList" :key="index" class="menu"
></router-link>
<!-- Linkage css style .router-link-active {} -->

Programming: path and query match, name and params match. They cannot be used interchangeably, otherwise they will not take effect

//With query parameters, equivalent to / register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
//Or name the route, see the next chapter
router.push({ name: 'user', params: { userId: '123' }})

4. Named routes and named views

4.1. Named route

It is more convenient to identify a route by a name, especially when linking a route or performing some jumps

export const routes = [
  {
    path: "/login/:userId",
    name: "Login",
    component: () => import("./views/login")
  },
]

To link to a named route, you can pass an object to the to attribute of the router link

<router-link :to="{ name: 'Login', params: { userId: 123 }}">
    User
</router-link>

Equivalent to

router.push({ name: 'Login', params: { userId: 123 } })

Equivalent to

/login/123

4.2. Named view

Sometimes you want to display multiple views at the same time (at the same level) rather than nested display. For example, you can create a layout with two views, @ sidebar (side navigation) and @ main (main content). At this time, naming the view comes in handy. You can have multiple individually named views in the interface instead of just one single exit. If "router view" has no name set, it defaults to "default".

<router-view></router-view>
<router-view name="a"></router-view>
<router-view name="b"></router-view>

that

export const routes = [
  {
    path: '/',
    components: {
      default: Foo,
      a: Bar,
      b: Baz
    }
  },
]

5. Dynamic routing parameter transmission (improved writing method)

Using $route in a component will form a high coupling with its corresponding route, so that the component can only be used on some specific URL s, which limits its flexibility

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [{ path: '/user/:id', component: User }]
})

The advanced writing method is decoupled by {props}

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // For routes containing named views, you must add the 'props' option for each named view separately:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

6. Navigation guard

6.1. Global front guard

// To the path to be accessed
// From stands for which path to jump from
// next is a function that indicates release 
// next() release 
// next(/login) force jump
// next(false) interrupted the navigation
// next(new Error()) the navigation guard threw an error
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})

6.2. Global post hook

You can also register global post hooks. However, unlike guards, these hooks will not accept the {next} function and will not change the navigation itself

router.afterEach((to, from) => {
  // ...
})

6.3. Route exclusive guard

You can directly define "before enter" guard on routing configuration:

export const routes = [
  {
	path: '/foo',
	component: Foo,
	beforeEnter: (to, from, next) => {
	// ...
	}
  }
]

7. Routing meta information

When defining a route, you can configure the {meta} field:

export const routes = [
	{
	  path: '/foo',
	  component: Foo,
	  children: [
		{
		  path: 'bar',
		  component: Bar,
		  meta: { requiresAuth: true }
		}
	  ]
	}
]

All route records matched by a route will be exposed as $route of the $route} object (and the route object in the navigation guard) Matched array. Therefore, we need to traverse $route Matched , to check the , meta , field in the routing record.

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
   ...
  } else {
    next() // Make sure to call next()
  }
})

That's about it

 

 

Added by peterg0123 on Mon, 24 Jan 2022 11:16:22 +0200