通过路由器链接传递道具

时间:2021-03-31 15:55:00

标签: vue.js vue-router router vuejs3 vue-props

我是 Vue 3 路由器的新手,所以真的需要帮助。 我正在尝试通过路由器链接传递道具。

所以,我有一个组件 Post,其中一个 prop post 是一个对象。

Post.vue

export default defineComponent({
  name: 'Post',
  props: {
    post: {
      type: Object as PropType<Post>,
      required: true,
    },
  },

我有一个 EditPostForm 组件,其中应该与 Post 组件中的对象完全相同。

EditPostForm.vue

export default defineComponent({
  name: 'EditPostForm',
  props: {
    post: {
      type: Object as PropType<Post>,
      required: true,
    },
  },

这就是 Post 组件中的路由器链接。

Post.vue

<router-link
  class="..."
  :to="{
     path: '/post/edit',
     props: post,
     query: { post: post.id },
   }"
   >Edit
</router-link>

路由器/index.ts

{
    path: '/post/edit',
    name: 'Edit Post',
    component: EditPostForm,
    props: Object as PropType<Post>,
},

我遇到了一个错误

错误

[Vue warn]: Missing required prop: "post" 
  at <EditPostForm fullPath="/post/edit?post=3" hash="" query= {post: "3"}  ... > 
  at <RouterView> 
  at <App>

1 个答案:

答案 0 :(得分:1)

据我所知,你不能直接使用 <router-link> 传递 props,但你可以设置 vue-router 将路由 params 作为 props 传递给组件:< /p>

{
    path: '/post/edit/:prop1/:prop2/:prop3', // set your desired props as params in the url
    name: 'Edit Post',
    component: EditPostForm,
    props: true, // set props to true, this will pass the url params as props
},

然后,在您的模板中,您可以在 params 中指定 :to 属性:

<router-link
  class="..."
  :to="{
     path: '/post/edit',
     params: post, // <-- changed 'props' to 'params'
     query: { post: post.id },
   }"
   >Edit
</router-link>

也可以通过 Object modeFunction moderead more about them in the docs 来传递道具。

对象模式没有用,因为它主要用于静态道具,但如果我上面提供的内容不适用于您的用例,也许您可​​以使用功能模式。