VueRouter basic review

Highlights at a glance

Insert picture description here

Mind map link: https://www.processon.com/view/link/602f374e6376891d5f86f8d1

Basic use of VueRouter

HTML
1. Create a placeholder for the routing component

<!-- 路由匹配到的组件将渲染在这里 -->
<router-view>

2. Create a link

<!-- 通过传入 `to` 属性指定链接 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>

JS
1. Introduction

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

2. Register the routing plugin

Vue.use(VueRouter)

3. Define routing rules

const routes = [
	{
    
    
		path:"/",
		name:"index",
		component: Index
	}
]

4. Create a routing object

const router = new VueRouter({
    
    
	routes
})

5. Register the router object in the Vue instance

new Vue({
    
    
  router,
  render: h => h(App)
}).$mount("#app")

After injection of the router, by any component in the this.$routeraccess routers, you can also this.$routeaccess the current route.


$router

The router, the vueRouter instance, is passed in through the router configuration in the Vue root instance.

Props

Attributes Types of Description
app Instance view Vue root instance with router configured
mode string The mode used by the route
currentRoute Route The routing information object corresponding to the current route (ie $route)
START_LOCATION Route Display the initial routing address in the format of the routing object, that is, the place where the routing starts. Can be used in navigation guards to distinguish initial navigation

Methods

method Description Remarks
beforeEach
beforeResolve
afterEach
push
replace
go
back
forward
getMatchedComponents
resolve
addRoutes
addRoute
addRoute
getRoutes
onReady
onError

$route

The current route object represents the status information of the currently activated route. Immutable, a new object will be generated after each successful navigation.

Props

Attributes Types of Description
path string The path corresponding to the current route is always resolved as an absolute path, such as " /foo/bar"
params Object A key/value object that contains dynamic fragments and full-match fragments. Such as: pattern /user/:username, matching path /user/evan,$route.params ={ username: 'evan' }
query Object A key/value object that represents URL query parameters. For example, for the path /foo?user=1, there are$route.query.user == 1
hash string The hash value of the current route (with #)
fullPath string The parsed URL, including the query parameters and the full path of the hash
matched Array An array containing routing records of all nested path fragments of the current route
name string The name of the current route
redirectedFrom string If there is a redirection, it is the name of the route from which the redirection originated

Dynamic routing

use

All routes that match a certain pattern are all mapped to the same component. For example, the product detail page uses the Detail component.

const router = new VueRouter({
    
    
  routes: [
    // 动态路径参数 以冒号开头
    {
    
     
    	path: '/detail/:id', 
    	component: Detail
    }
  ]
})

Get path parameters

  • Directly through the $route.paramsacquisition. "Path argument" colon :mark. When a route is matched, the parameter value will be set to this.$route.params, which can be used in each component.
mode Match path $route.params
/user/:username /user/evan { username: ‘evan’ }
/user/:username/post/:post_id /user/evan/post/123 { username: ‘evan’, post_id: ‘123’ }
  • Receive through props. Need to be set in the routing configurationprops:true
const router = new VueRouter({
    
    
  routes: [
    {
    
     
    	path: '/detail/:id', 
    	component: Detail,
    	props: true //通过props把参数传递给组件
    }
  ]
})

Respond to routing parameter changes

注意!当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。这意味着组件的生命周期钩子不会再被调用
需要对路由参数的变化作出响应,可以通过以下两种方式:

1. watch (监测变化) $route 对象

const User = {
    
    
  template: '...',
  watch: {
    
    
    $route(to, from) {
    
    
      // 对路由变化作出响应...
    }
  }
}

2. 使用 beforeRouteUpdate 进行导航守卫

const User = {
    
    
  template: '...',
  beforeRouteUpdate (to, from, next) {
    
    
      // 对路由变化作出响应...
      // 记得要调用 next()
  }
}

路由嵌套

需要进行路由嵌套,在路由规则中使用 children 配置即可:

const router = new VueRouter({
    
    
  routes: [
    {
    
     path: '/user/:id', component: User,
      children: [
        {
    
    
          // 当 /user/:id/profile 匹配成功,UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
    
    
          // 当 /user/:id/posts 匹配成功,UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        },
        {
    
     
	        // 提供一个【空的】子路由,当 /user/:id 匹配成功,UserHome 会被渲染在 User 的 <router-view> 中
	        // 如果没有提供这个空的子路由,User 的出口不会渲染任何东西。
        	path: '', 
        	component: UserHome
        }
      ]
    }
  ]
})

编程式导航

  • router.push
  • router.replace
  • router.go

router.push(location, onComplete?, onAbort?)

参数可以是一个字符串路径,或者一个描述地址的对象

// 字符串
router.push('home')

// 对象
router.push({
    
     path: 'home' })

// 命名的路由(可以使用 name 而不用 path)
router.push({
    
     name: 'user'}) 

// 命名的路由,带参数
router.push({
    
     name: 'user', params: {
    
     userId: '123' }})  // => /user/123 

// 带查询参数
router.push({
    
     path: 'register', query: {
    
     plan: 'private' }}) // => /register?plan=private

注意:如果提供了 path,params 会被忽略。

const userId = '123'

// name + params
router.push({
    
     name: 'user', params: {
    
     userId }}) // -> /user/123

// 带有手写参数的 path
router.push({
    
     path: `/user/${
      
      userId}` }) // -> /user/123

// 错误使用:这里的 params 不生效
router.push({
    
     path: '/user', params: {
    
     userId }}) // -> /user 

router.replace(location, onComplete?, onAbort?)

router.push 基本相同,唯一的不同就是,它不会向 history 添加新记录,而是替换当前记录。

router.go(n)

参数是一个整数,意思是在 history 记录中向前或者后退多少步。类似 window.history.go(n)


VueRouter 路由守卫

1)全局级别

前置守卫:beforeEach

解析守卫:beforeResolve

导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后调用

后置钩子:afterEach

不会接受 next 函数也不会改变导航本身。

2)路由级别

前置守卫:beforeEnter

在路由规则中给特定路由进行配置。

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

3)组件级别

beforeRouteEnter

The component instance has not been created, and the component instance cannot be obtained this. But you can get the component instance through the callback in the next (callback is executed when the navigation is confirmed, and the component instance is used as the parameter of the callback method. Only beforeRouteEnter supports passing callback)

beforeRouteEnter (to, from, next) {
    
    
  next(vm => {
    
    
    // 通过 `vm` 访问组件实例
  })
}

beforeRouteUpdate

Called when the current route is changed, but the component is reused

beforeRouteLeave

Called when the navigation leaves the corresponding route of the component, and the component instance can still be obtained at this time this

4) Parameter analysis

router.***((to, from, next) => { ...})

  • to: Route, the target route object to be entered
  • from: Router, the route that the current navigation is about to leave
  • next: Function, call this method to resolve this hook

Guess you like

Origin blog.csdn.net/lychee_xiahua/article/details/113532292