【问题标题】:Passing props through a router-link通过路由器链接传递道具
【发布时间】:2021-06-27 15:56:35
【问题描述】:

我是 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>

router/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>

【问题讨论】:

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


    【解决方案1】:

    据我所知,您不能直接使用 &lt;router-link&gt; 传递道具,但您可以设置 vue-router 将路由 params 传递为 props 给组件:

    {
        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
    },
    

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

    <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来完成。

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

    【讨论】:

    • 没有帮助。获取方式错误:No match found for location with path "/post/edit/"Path "/post/edit/" was passed with params but they will be ignored. Use a named route alongside params instead. 但感谢您的回复!
    • @kadeikin 您是否将 router/index.ts 中的路径设置为“/post/edit/:post”。另外,在上面的路由器链接中:参数应该是 {post} 而不是 post
    • @priosshrsth 是的,我做到了。 path: '/post/edit/:post'path: '/post/edit', params: { post },
    • @kadeikin 您是否也更改了router/index.ts 中的props: true 集?在路由器配置中,props 是布尔值,但您已将其设置为 Object as PropType&lt;Post&gt;
    • @tony19 是的,我做到了
    猜你喜欢
    • 2021-05-24
    • 2019-03-23
    • 2023-03-31
    • 2017-08-10
    • 2021-09-13
    • 2023-04-03
    • 2021-04-12
    • 2021-08-21
    • 2021-05-30
    相关资源
    最近更新 更多