Reputation: 647
So I've got a vue router and for one of the views, I want to pass a prop of type Object, but when I pass the prop, it ends up not as an object but as [object Object]
.
Heres how I set up the route for this page:
{
path: '/blogpage/',
name: 'BlogPage',
component: () => import('../subviews/BlogPage.vue'),
props: (route) => ({
blog: route.params.blog,
...route.params
})
}
Here's the view I'm trying to go to:
<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>
And the first tag of my router link going there:
<router-link :to="{ name: 'BlogPage',
params: { blog: blog }}">
For now, I'm using dummy data for the blog page and the dummy blog object looks like this:
{
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"
}
Right now, the BlogPage view looks like this and the h1 has no text:
Upvotes: 2
Views: 5010
Reputation: 385
Assuming the object is in the route parameters and you're not using the composition API, in your view's <script>
tag, you can add the blog
object to the data
object.
export default {
name: 'BlogPage',
data: function() {
return {
blog: this.$route.params.blog,
};
},
}
But, because you're passing in the object via the route parameters, which only accepts strings, the object is converted to its string representation: [object Object]
. To work around this, first, you need to change the parameter to be a string version of the object. This can be accomplished with JSON.stringify
. So your <router-link>
turns into <router-link :to="{ name: 'BlogPage', params: { blog: JSON.stringify(blog) }}">
. Then, you have to update the data object in the view by parsing the passed in object with JSON.parse
. To do this, replace this.$route.params.blog
with JSON.parse(this.$route.params.blog)
.
Upvotes: 6