【问题标题】:How to pass Object through vue router as prop如何通过 vue 路由器将对象作为道具传递
【发布时间】:2021-07-30 18:11:11
【问题描述】:

所以我有一个 vue 路由器,对于其中一个视图,我想传递一个 Object 类型的道具,但是当我传递道具时,它最终不是作为对象,而是作为 [object Object]

以下是我为此页面设置路线的方式:

{
    path: '/blogpage/',
    name: 'BlogPage',
    component: () => import('../subviews/BlogPage.vue'),
    props: (route) => ({
        blog: route.params.blog,
        ...route.params
    })
  }

这是我要查看的视图:

<template>
    <div class="page" v-on:click="test">
        AJSFHDKOIFHNK
        {{blog}}
        <h1>{{ blog.title }}</h1>
    </div>
</template>

<script>
export default {
    name: 'BlogPage',
    props: {
        blog: Object,
    },
}
</script>

我的路由器链接的第一个标签去那里:

<router-link :to="{ name: 'BlogPage', 
           params: { blog: blog }}">

目前,我正在为博客页面使用虚拟数据,虚拟博客对象如下所示:

{
    title: 'Blog Post 1',
    content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis temporibus exercitationem aut unde provident mollitia?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio, quas doloribus impedit aut cum expedita molestiae beatae incidunt similique, aliquam ea nemo exercitationem libero atque sunt autem. Inventore, nostrum veritatis. Nostrum eum aliquid soluta praesentium ullam distinctio temporibus eius doloremque dicta doloribus, et labore vitae odio impedit maiores ratione!',
    date: '2018-01-01',
    author: 'John Doe',
    id: "90876tygui"
}

现在,BlogPage 视图看起来像这样,并且 h1 没有文本:

【问题讨论】:

  • 所以对象在路由参数中?
  • 是的,我想是的。

标签: javascript vue.js vue-router


【解决方案1】:

假设对象在路由参数中并且您没有使用组合 API,则可以在视图的 &lt;script&gt; 标记中将 blog 对象添加到 data 对象中。

export default {
    name: 'BlogPage',
    data: function() {
        return {
            blog: this.$route.params.blog,
        };
    },
}

但是,由于您通过仅接受字符串的路由参数传入对象,因此该对象被转换为其字符串表示形式:[object Object]。要解决此问题,首先,您需要将参数更改为对象的字符串版本。这可以通过JSON.stringify 完成。所以你的&lt;router-link&gt; 变成了&lt;router-link :to="{ name: 'BlogPage', params: { blog: JSON.stringify(blog) }}"&gt;。然后,您必须通过使用JSON.parse 解析传入的对象来更新视图中的数据对象。为此,请将this.$route.params.blog 替换为JSON.parse(this.$route.params.blog)

【讨论】:

  • 非常感谢您的回答,但不幸的是结果还是一样,当我在 BlogPage 的模板中做{{blog}} 时,它仍然以 [object Object] 的形式显示为字符串。
  • 数据正在通过您的方法和我之前使用的方法进入 BlogPage 组件,但问题是对象正在被转换为字符串“[object Object]”方式。
  • 对象是什么样子的?
  • 我已经编辑了我的问题以包含更多信息。
  • 哦!路由参数不能是对象,它必须是字符串。因此,当您添加参数时,它会将其转换为字符串。因此,当您将其添加到参数时,在您的 &lt;router-link&gt; 标记中,您需要将 JSON.stringify(blog) 放在那里。这将使它成为:&lt;router-link :to="{ name: 'BlogPage', params: { blog: JSON.stringify(blog) }}"&gt;。然后,在视图中,将this.$route.params.blog 替换为JSON.parse(this.$route.params.blog)
猜你喜欢
  • 2018-11-03
  • 2020-04-03
  • 2019-09-04
  • 1970-01-01
  • 2018-02-12
  • 2021-06-27
  • 2023-04-03
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多