Vue-router之路由参数传递

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/grapelove01/article/details/82585528

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>

点击 app 链接,跳转 todo 页面 ,本地url 路径 localhost:8000/app/123

通过 $route 可以拿到路由信息

// client/app.vue
export default {
  mounted () {
    console.log(this.$route)
  }
}
// 控制台
{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 传 params

通过这种方式,不需要 this.$route 的写法,它会和 vue-router 有一定的耦合,如果其升级,用法可能会变;如果组件使用了 this.$router 的写法,就不能作为单纯的组件拿到其他地方用,只能作为 route 配置中的 component 去用。

通过 props 的方式,实现了解耦,可以在其他地方使用组件,只需要传 props 即可。

// client/config/routes.js
export default [
  {
    path: '/app/:id', // 把 :id 作为 props 传到 Todo 中
    props: true, // 通过 props 来传 params
    component: Todo,
  }
]
export default {
  props: ['id'],
  mounted () {
    console.log(this.id) // 控制台 123
  }
}

props 指定值

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

props 函数

通过 query 指定 id

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

query

在路径上直接添加,http://localhost:8000/app/123?a=123&b=456

通过 $route 拿到 query

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

猜你喜欢

转载自blog.csdn.net/grapelove01/article/details/82585528