所以我有一个 vue 路由器,对于其中一个 View ,我想传递一个 Object 类型的 prop,但是当我传递该 prop 时,它最终不是作为一个对象,而是作为 [object Object ]
。
这是我如何设置此页面的路线:
{
path: '/blogpage/',
name: 'BlogPage',
component: () => import('../subviews/BlogPage.vue'),
props: (route) => ({
blog: route.params.blog,
...route.params
})
}
这是我想要访问的 View :
<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"
}
最佳答案
假设该对象位于路由参数中并且您没有使用组合 API,则在您的 View 的 <script>
中标签,可以添加blog
反对data
对象。
export default {
name: 'BlogPage',
data: function() {
return {
blog: this.$route.params.blog,
};
},
}
但是,由于您通过路由参数传入对象,该参数仅接受字符串,因此该对象将转换为其字符串表示形式:[object Object]
。要解决此问题,首先需要将参数更改为对象的字符串版本。这可以通过 JSON.stringify
来完成。所以你的<router-link>
变成 <router-link :to="{ name: 'BlogPage', params: { blog: JSON.stringify(blog) }}">
。然后,您必须通过使用 JSON.parse
解析传入的对象来更新 View 中的数据对象。 。为此,请替换 this.$route.params.blog
与 JSON.parse(this.$route.params.blog)
.
关于javascript - 如何通过 vue router 将对象作为 prop 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68595444/