Route parameter passing of Vue router

Keywords: Vue

params

// client/config/routes.js
export default [
  {
    path: '/app/:id',
  }
]
// client/app.vue
<template>
  <div id="app">
    <router-link to="/app/123">app</router-link>
  </div>
</template>

Click the app link to jump to the todo page, local url path localhost:8000/app/123

Get route information through $route

// client/app.vue
export default {
  mounted () {
    console.log(this.$route)
  }
}
// Console
{name: "app", meta: {...}, path: "/app/123", hash: "", query: {...}, ...}
fullPath:"/app/123"
hash:""
matched:[{...}]
meta:{title: "this is app", description: "xxx"}
name:"app"
params:{id: "123"}
path:"/app/123"
query:{}
__proto__:Object

props to params

In this way, there is no need to write this.$route. It will be coupled with Vue router to some extent. If it is upgraded, its usage may change. If the component uses this.$route, it cannot be used as a simple component in other places, but only as a component in the route configuration.

Through the way of props, decoupling is realized. Components can be used in other places, just passing props.

// client/config/routes.js
export default [
  {
    path: '/app/:id', // Pass: id as props to Todo
    props: true, // Passing params through props
    component: Todo,
  }
]
export default {
  props: ['id'],
  mounted () {
    console.log(this.id) // Console123
  }
}

props specified value

// client/config/routes.js
export default [
  {
    path: '/app/:id', 
    props: {
      id: '456' 
    },
    component: Todo,
  }
]

props function

Specify id through query

// client/config/routes.js
export default [
  {
    path: '/app/:id', 
    props: (route) => ({ id: route.query.b }) // Specify id through query
    component: Todo,
  }
]

query

Add directly on the path, http://localhost:8000/app/123?a=123&b=456

Get query through $route

query: {a: "123", b: "456"}

Posted by macman90 on Fri, 03 Jan 2020 05:45:04 -0800