梗概

  • /users/8这个路由把这个8作为参数传给对应Vue 组件

实例

传递给组件的prop中

传递静态参数

Object mode

When props is an object, this will be set as the component props as-is. Useful for when the props are static.

const routes = [
  {
    path: '/promotion/from-newsletter',
    component: Promotion,
    props: { prop1: value1 }
  }
]

Function mode

You can create a function that returns props. This allows you to cast parameters into other types, combine static values with route-based values, etc.

const routes = [
  {
    path: '/search',
    component: SearchUser,
    props: route => ({ prop1: value1 })
  }
]

传递动态参数

We can then configure the route to pass the id param as a prop by setting props: true:

const routes = [
  { path: '/user/:id', component: User, props: true }
]

传递给路由实例中

Very often we will need to map routes with the given pattern to the same component. For example, we may have a User component which should be rendered for all users but with different user IDs. In Vue Router we can use a dynamic segment in the path to achieve that, we call that a param:

import User from './User.vue'
// these are passed to `createRouter`
const routes = [
  // dynamic segments start with a colon
  { path: '/users/:id', component: User },
]

Now URLs like /users/johnny and /users/jolyne will both map to the same route. A param is denoted by a colon :. When a route is matched, the value of its params will be exposed as route.params in every component. Therefore, we can render the current user ID by updating User’s template to this:

<template>
  <div>
    <!-- The current route is accessible as $route in the template -->
    User {{ $route.params.id }}
  </div>
</template>

You can have multiple params in the same route, and they will map to corresponding fields on route.params. Examples:

patternmatched pathroute.params
/users/:username/users/eduardo{ username: 'eduardo' }
/users/:username/posts/:postId/users/eduardo/posts/123{ username: 'eduardo', postId: '123' }