[vue2] Detailed explanation of vue-router

This article mainly explains the detailed description of vue-router. If you can actually refer to my other article in the enterprise project, the link is placed in the 7. Notes section of this articleinsert image description here

1.router-link

<router-link>Allows users to (click) navigate in an application with routing capabilities, can change URLs without reloading the page, handles URL generation and encoding.

Attributes type illustrate
to String/Object Destination Route/Destination Object
replace Boolean leave no navigation history
append Boolean Add path /a => /a/b after the current path
tag String/Object Specify what kind of label to render
active-class String/Object The Class used when activating
<router-link :to="{ path: '/login'}" replace tag="span"></router-link>

2.router-view

<router-view>Is a functional component used to render the view component matched by the path, and will display the component corresponding to the url.

//方式一
<router-view></router-view>
//方式二 name是router设置里的name,会渲染对应的路由配置中 components下的相应组件
<router-view name="music"></router-view>

3. Route parameter props

3.1 Use the Boolean method:

Router configuration file, write parameters after the route, and set props to true

 {
    
    
        path: '/music',
        name: 'music',
        component: () => import(/* webpackChunkName: "home" */ '@/pages/music/index.vue'),
        props: true,
        meta: {
    
    
          title: '音乐',
          current: '/music',
        },
      },

On page A, set the parameters params that need to be passed in the jump

//方式一
<router-link :to="{name:'music', params: {id: 'aaaaa'}}">跳转</router-link>
//方式二
toNext() {
    
    
    this.$router.push({
    
    
    	name: 'music',
    	params: {
    
    
    		id: 'aaaaa'
    	}
    })
}

On the page B that you jumped to, get parameters through props or this.$params

//方式一
props: {
    
    
	id: {
    
    
		type: String,
		default: ''
	}
}
//方式二
this.$params.id


3.2 Object mode
router configuration file

   {
    
    
        path: '/music',
        name: 'music',
        component: () => import(/* webpackChunkName: "home" */ '@/pages/music/index.vue'),
        props: {
    
    
          id: route.query.id,  //使用query
          age: route.params.name  //使用params
        },
        meta: {
    
    
          title: '音乐',
          current: '/music',
        },
      },

On page A, set the jump

//方式一
<router-link :to="{name:'music',query: {id: 'aaaaa'}, params:{name:'音乐'}}" >跳转</router-link>
//方式二
toNext() {
    
    
	this.$router.push({
    
    
		name: 'music'
		query: {
    
    
			id: 'aaaaa'
		},
		params: {
    
    
			name: '音乐'
		}
	})
}

On the page B that you jumped to, get parameters through props or this.$params

//方式一
props: {
    
    
	id: {
    
    
		type: String,
		default: ''
	},
	name: {
    
    
		type: String,
		default: ''
	}
}
//方式二
this.$route.query.id
this.$route.params.name


4. Routing Guard

The navigation guard provided by vue-router is mainly used to guard the navigation by jumping or canceling

parameter illustrate
to The target routing object to be entered
from The route the current navigation is leaving
next callback method

For example:

router.beforeEach((to, from, next) => {
    
    
//如果没有登录则,跳转login,否则进行下一步
  if (to.name !== 'Login' && !isAuthenticated) next({
    
     name: 'Login' })
  else next()
})

Among them, next has the following usage methods

method illustrate
next() proceed to the next hook
next(false) Interrupt navigation, if the URL has been changed, reset to the address from
next(‘/’) Interrupt the current jump and go to other addresses, you can set the routing object
next(error) Navigation is terminated and an error is passed to onError()

4.1 The global parsing guard beforeResolve
router.beforeResolve is to get data or perform any other operations. It will be triggered every time you navigate, but make sure that the parsing guard is called correctly before the navigation is confirmed and after the guard and asynchronous routing components in all components are parsed. .

router.beforeResolve(async to => {
    
    
  if (to.meta.requiresCamera) {
    
    
    try {
    
    
      await askForCameraPermission()
    } catch (error) {
    
    
      if (error instanceof NotAllowedError) {
    
    
        // ... 处理错误,然后取消导航
        return false
      } else {
    
    
        // 意料之外的错误,取消导航并把错误传给全局处理器
        throw error
      }
    }
  }
})


4.2 The global post-hook afterEach
post-guard will not accept the next function and will not change the navigation itself

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


4.3 Routing exclusive guard beforeEnter
You can directly define a dedicated beforeEnter guard in the routing configuration, which is the same as the method parameter of the global pre guard. beforeEnterGuards are only triggered when entering a route, not when params, query or hash changes.

For example: from /users/2 to /users/3 or from /users/2#info to /users/2#projects. They are only triggered when navigating from a different route

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/music',
      component: () => import(/* webpackChunkName: "home" */ '@/pages/music/index.vue'),
      beforeEnter: (to, from, next) => {
    
    
        // ...
      }
    }
  ]
})


4.4 Guards within components

beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave

const UserDetails = {
    
    
  template: `...`,
  beforeRouteEnter(to, from) {
    
    
    // 在渲染该组件的对应路由被验证前调用
    // 不能获取组件实例 `this` !
    // 因为当守卫执行时,组件实例还没被创建!
  },
  beforeRouteUpdate(to, from) {
    
    
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 `/users/:id`,在 `/users/1` 和 `/users/2` 之间跳转的时候,
    // 由于会渲染同样的 `UserDetails` 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 因为在这种情况发生的时候,组件已经挂载好了,导航守卫可以访问组件实例 `this`
  },
  beforeRouteLeave(to, from) {
    
    
    // 在导航离开渲染该组件的对应路由时调用
    // 与 `beforeRouteUpdate` 一样,它可以访问组件实例 `this`
  },
}


5. Complete navigation analysis process

1. Navigation is triggered.

2. Call the beforeRouteLeave guard in the deactivated component.

3. Call the global beforeEach guard.

4. Call the beforeRouteUpdate guard (2.2+) in the reused component.

5. Call beforeEnter in the routing configuration.

6. Parse the asynchronous routing component.

7. Call beforeRouteEnter in the activated component.

8. Call the global beforeResolve guard (2.5+).

9. Navigation is confirmed.

10. Call the global afterEach hook.

11. Trigger DOM update.

12. Call the callback function passed to next in the beforeRouteEnter guard, and the created component instance will be passed in as the parameter of the callback function.


6. Routing meta information

If you want to attach arbitrary information to the route, such as transition name, who can access the route, etc., you can use metaattributes, the code is as follows

    {
    
    
        path: '/home',
        name: 'home',
        component: () => import(/* webpackChunkName: "home" */ '@/pages/home/home.vue'),
        meta: {
    
    
          title: '首页',
          current: '/home',
        },
      },
//方法一,在vue页面获取
this.$route.meta.title
//方法二 在导航守卫获取
router.beforeEach((to, from) => {
    
    
	console.log(to.meta.title)
})

7. Points to note

1. Router-vue official website address : https://router.vuejs.org/zh/guide/
2. Router has two modes, namely history and hash, the default is hash, you can refer to my construction project documentation: [ vue create] 2. Configure Esline, less, nprogress, ant-design-vue, environment variables env, axios, vuex, Router, route guard and login page

Guess you like

Origin blog.csdn.net/weixin_43861689/article/details/129623194