通过路由器链接传递道具

kad*_*kin 5 router vue.js vue-router vue-props vuejs3

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

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

后vue

export default defineComponent({
  name: 'Post',
  props: {
    post: {
      type: Object as PropType<Post>,
      required: true,
    },
  },
Run Code Online (Sandbox Code Playgroud)

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

EditPostForm.vue

export default defineComponent({
  name: 'EditPostForm',
  props: {
    post: {
      type: Object as PropType<Post>,
      required: true,
    },
  },
Run Code Online (Sandbox Code Playgroud)

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

后vue

<router-link
  class="..."
  :to="{
     path: '/post/edit',
     props: post,
     query: { post: post.id },
   }"
   >Edit
</router-link>
Run Code Online (Sandbox Code Playgroud)

路由器/index.ts

{
    path: '/post/edit',
    name: 'Edit Post',
    component: EditPostForm,
    props: Object as PropType<Post>,
},
Run Code Online (Sandbox Code Playgroud)

我收到一个错误

错误

[Vue warn]: Missing required prop: "post" 
  at <EditPostForm fullPath="/post/edit?post=3" hash="" query= {post: "3"}  ... > 
  at <RouterView> 
  at <App>
Run Code Online (Sandbox Code Playgroud)

Cat*_*oha 9

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

{
    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
},
Run Code Online (Sandbox Code Playgroud)

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

<router-link
  class="..."
  :to="{
     path: '/post/edit',
     params: post, // <-- changed 'props' to 'params'
     query: { post: post.id },
   }"
   >Edit
</router-link>
Run Code Online (Sandbox Code Playgroud)

也可以通过Object mode或来传递道具Function mode请在文档中阅读有关它们的更多信息

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