I am trying to create the following functionality
1 array of questions gets passed as a prop in a vue link like so
<router-link
:to="{
name: 'finder_step',
params: {
id: 2,
questions: [
{
id: 'q1',
body: 'one'
},
{
id: 'q2',
body: 'two'
}
]
}
}"
>
Step 2
</router-link>
where the questions prop is an array of objects with an id and body text. However, the issue I am stuck on is that my output then becomes [ "[object Object]", "[object Object]" ]
What I am understanding is that my object is getting converted into a string at some point. What I dont understand is why, and what the proper syntax I need to use is.
Here is how I loop over my array in the vue file.
<template>
<div>
<p>ID: {{ id }}</p>
<p>Question: {{ questions }}</p>
<li
v-for="question in questions"
:key="question.id"
>
{{ question.body }}
</li>
</div>
</template>
<script>
export default {
props: {
id: { type: String, default: '' },
questions: {
type: Array,
id: String,
body: String
}
}
}
</script>
Route params are intended to be strings in the route's URL for dynamic path parameters , so Vue Router automatically encodes them .
One workaround is to use JSON.stringify
on any params that are not strings/numbers (ie, questions
in this case):
<router-link
:to="{
name: 'finder_step',
params: {
id: 2, 👇
questions: JSON.stringify([
{
id: 'q1',
body: 'one'
},
{
id: 'q2',
body: 'two'
}
])
}
}"
>
Step 2
</router-link>
Then JSON.parse
the prop in your component as a computed property :
export default {
props: {
questions: Array
},
computed: {
computedQuestions() {
if (typeof this.questions === 'string') {
return JSON.parse(this.questions)
} else {
return this.questions
}
}
}
}
And use the computed prop in your template:
<ul>
<li
v-for="question in computedQuestions"
:key="question.id"
>
{{ question.body }}
</li>
</ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.