Recently, I reviewed the vUE family bucket, so I made a special note of it.

1, the router – the view


is a functional component that renders the view component to which the path matches. It can be used with
and

. If both are used together, make sure to use

on the inner layer.


<router-view></router-view> <! - or - ><router-view name="footer"></router-view>
Copy the code

If

has a name, the corresponding component under Components in the corresponding routing configuration is rendered.

2, the router – the link

The

tag allows users to (click) navigate through applications with routing capabilities.

attribute type instructions
to String/Object Destination route/destination location object
replace Boolean No navigation records are left
append Boolean If you add path /a to the current path, go to /a/b
tag String Specifies what label to render to
active-class String The Class used when activating
<router-link :to="{ path: '/login'}" replace tag="span"></router-link>
Copy the code

3. Redirect

The root route redirects to login

const router = new VueRouter({
  routes: [{path: '/'.redirect: '/login'}]})Copy the code

Dynamically returns the redirect target

const router = new VueRouter({
  routes: [{path: '/a'.redirect: to= > {
      // The method receives the destination route as an argument
      // Return redirects the string path/path object}}}])Copy the code

4. Route alias

When a route accesses /b, the URL remains /b, but the route matches/A

const router = new VueRouter({
  routes: [{path: '/a'.component: A, alias: '/b'}]})Copy the code

5, routing parameter props

Avoid over-coupling with $route by using props, so you can use props to receive parameters directly in the component

5.1. Boolean mode

Write parameters after the route and set props to true

{
	path: '/vuex/:id'.name: 'Vuex'.component: () = > import('@/view/vuex'),
	props: true.mate: {
		title: 'vuex'}}Copy the code

Sets the parameter params that the jump needs to pass

< the router - link: to = "{name: 'Vuex, params: {id:' 99999 '}}" tag = "h1" > jump < / router - the link > <! - or - > toNext () {this. $router. Push ({name: 'Vuex, params: {id:' 99999 '}})}Copy the code

To jump to the past page, use props or this.$params

props: {
	id: {
		type: String,
		default: ''
	}
}
<!--或者-->
this.$params.id
Copy the code

5.2. Object Mode

In the route, set props as an object with static data

{
	path: '/vuex',
	name: 'Vuex',
	component: () => import('@/view/vuex'),
	props: {
		id: '99999'
	},
	mate: {
		title: 'vuex'
	}
}
Copy the code

jump

< the router - link: to = "{name: 'Vuex'}" tag = "h1" > jump < / router - the link > <! - or - > toNext () {this. $router. Push ({name: 'Vuex})}Copy the code

To jump to the past page, use props or this.$params

props: {
	id: {
		type: String,
		default: ''
	}
}
<!--或者-->
this.$params.id
Copy the code

Note: This applies only to static data

5.3. Functional patterns

In the route, set props to Function, and return an object, either query or params, to props

{ path: '/vuex', name: 'Vuex', component: () => import('@/view/vuex'), props: route => ({ <! --query--> id: route.query.id, <! --params--> age: route.params.age }), mate: { title: 'vuex' } }Copy the code

jump

< the router - link: to = "{name: 'Vuex, query: {id:' 99999 '}, params: {age: '20'}}" tag = "h1" > jump < / router - the link > <! - or - > toNext () {this. $router. Push ({name: 'Vuex, query: {id:' 999999 '}, params: {age: '20'}})}Copy the code

$route.params/this.$route.query

props: { id: { type: String, default: '' }, age: { type: String, default: '' } } <! $route.query this.$route.paramsCopy the code

6. Route guard

Route guard is mainly used to guard navigation by jumping or canceling.

6.1, global front-guard beforeEach

When a navigation is triggered, the global front-guard is called in the order it was created. The guard is parsed asynchronously, where the navigation waits until all the guards are parsed.

parameter instructions
to The destination route object to be entered
from The current navigation is about to leave the route
next The callback method

Next is used as follows

grammar instructions
next() Proceed to the next hook
next(false) Interrupts navigation and resets the URL to the address of from if it has been changed
next(‘/’) Interrupt the current jump and go to another address, you can set the route object
next(error) Navigation terminates and passes an error to onError()
const router = new VueRouter({ ... })

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

6.2. Global resolution guard beforeResolve

New in 2.5.0, similar to beforeEach, except that the parse guard is called before navigation is confirmed and after all the guards and asynchronous routing components are parsed.

router.eforeResolve((to, from, next) => {
  // ...
})
Copy the code

6.3. Global afterEach hook

The back guard does not accept the next function nor does it change the navigation itself

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

6.4, route exclusive guard beforeEnter

Exclusive beforeEnter guards can be defined directly on the route configuration, with the same method parameters as global front-guards.

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
Copy the code

6.5. Guards within components

  • beforeRouteEnter

The guard cannot access this because the guard is called before the navigation is confirmed, so the upcoming new component has not yet been created. You can access the component instance by passing a callback to Next. The callback is executed when the navigation is validated, and the component instance is taken as an argument to the callback method.

const Footer = { template: `... ', beforeRouteEnter(to, from, next) {next(VM => {// access component instance through 'VM'})}}Copy the code
  • BeforeRouteUpdate (2.2 New)

Called when the current route changes but the component is being reused, you can access the component instance this.

const Foo = { template: `... `, beforeRouteUpdate(to, from, next) { this.name = to.params.name next() } }Copy the code
  • beforeRouteLeave

Called when navigation leaves the corresponding route of the component and is usually used to prevent the user from leaving abruptly without saving the changes. This can be undone by next(false).

const Foo = { template: `... `, beforeRouteLeave(to, from, Next) {const answer = window.confirm(' Confirm to leave ') if (answer) {next()} else {next(false)}}}Copy the code

6.6. Complete navigation parsing process

  1. Navigation is triggered.
  2. Called in a deactivated componentbeforeRouteLeaveThe guards.
  3. Call globalbeforeEachThe guards.
  4. Called in a reused componentbeforeRouteUpdateGuard (+ 2.2).
  5. Called in the routing configurationbeforeEnter.
  6. Parse the asynchronous routing component.
  7. Called in the active componentbeforeRouteEnter.
  8. Call globalbeforeResolveGuard (+ 2.5).
  9. Navigation confirmed.
  10. Call globalafterEachHook.
  11. The triggerDOMThe update.
  12. callbeforeRouteEnterGuard passnextThe created component instance is passed in as an argument to the callback function.

7. Routing meta information

When defining routes, you can configure meta object fields to store the information corresponding to each route. Access via this.$route.meta, or via to.meta and from.meta in the route guard.

const router = new VueRouter({ routes: [ { path: '/index', name: 'Index', component: () = > import (' @ / view/index), meta: {title: 'homepage, rolu: [' admin', 'boss']}}]})Copy the code

8. Transitional dynamic effect

Just wrap the Transition tag around the router-view tag, and you can customize the animation. See the Transition component. You can also use watch in the parent component or app.js to listen for changes in $route and replace the transition component’s name property with different routes to achieve different animation effects.

<transition :name="transitionName">
  <router-view></router-view>
</transition>
Copy the code

Listening to the

watch: {
  '$route' (to, from) {
    const toD = to.path.split('/').length
    const fromD = from.path.split('/').length
    this.transitionName = toD < fromD ? 'slide-right' : 'slide-left'
  }
}
Copy the code

9. Rolling behavior

When creating a Router instance, you can provide a scrollBehavior method and receive to and FROM routing objects. The third parameter, savedPosition, is only available when triggered by the browser’s forward/back buttons.

const router = new VueRouter({
	mode: 'hash',
	routes,
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					resolve(savedPosition)
				}, 1000)
			})
		} else {
			return { x: 0, y: 0 }
		}
	}
})
Copy the code

10. Complete route configuration

Import Vue and VUe-Router, and then use router to define a set of routing information. Each route is an object, and the object has the following attributes

attribute type value
path String Component Path Information
name String The component named
component Function component
mate Object Meta information
children Object Zi lu by
redirect String redirect
props Boolean/Object/Function Parameter passing

The specific code is as follows:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
	{
		path: '/'.redirect: '/index'
	},
	{
		path: '/index'.name: 'Index'.component: () = > import(/* webpackChunkName: "index" */ '@/view/index'),
		mate: {
			title: 'home'.auth: false}}, {path: '/login'.name: 'Login'.component: () = > import(/* webpackChunkName: "login" */ '@/view/login'),
		meta: {
			title: 'login'.auth: false
		},
		children: [{path: 'children'.name: 'Children'.component: () = > import(/* webpackChunkName: "children" */ '@/view/children'),
				mate: {
					title: 'Nested child routing'.auth: false}}]}]const router = new VueRouter({
	mode: 'hash',
	routes
})

export default router
Copy the code

Note: Nested subroutes must place a

tag on the nested page.


If you think it is helpful, I am @pengduo, welcome to like and follow the comments; END

The articles

  • Use NVM to manage node.js version and change NPM Taobao image source
  • More detailed! Vue’s nine ways of communication
  • Wechat small program to achieve search keyword highlighting
  • Env files are used in vUE to store global environment variables and configure vUE startup and package commands
  • More detailed! Vuex hands-on tutorials

Personal home page

  • CSDN
  • GitHub
  • Jane’s book
  • Blog garden
  • The Denver nuggets