问题
Let's say I have this list of objects in Vue.JS
data () {
return{
examples: [
{
exampleID: 5,
exampleText: 'foo'
},
{
exampleID: 3,
exampleText: 'bar'
}
]
}
}
Now let's say I want to display the object with the exampleID of 3 in an element i created before
<Task
v-for="example in examples"
:key="example.exampleID"
:example="example"
/>
I want to display everything, that is in the object (the ID and the text)
Task component :
<template>
<div class="exercise">
<div class="exercise-id">
<h1>ID NUMBER: {{ example.exampleID }}</h1>
</div>
<div class="exercise-task">
<h2>{{ example.exampleText}}</h2>
</div>
</div>
</template>
<script>
export default {
name: 'Task',
props: ['example']
}
</script>
回答1:
You shouldn't use v-if
and v-for
in the same element, in this case i suggest to use a computed property that only return the desired example :
data () {
return{
examples: [
{
exampleID: 5,
exampleText: 'foo'
},
{
exampleID: 3,
exampleText: 'bar'
}
]
}
},
computed:{
myExample(){
return this.examples.find(ex=>ex.exampleID===3)
}
}
then render it like :
<Task :example="myExample"/>
回答2:
Another efficient way of doing it without v-for is
data () {
return{
examples: [
{
exampleID: 5,
exampleText: 'foo'
},
{
exampleID: 3,
exampleText: 'bar'
}
],
id: 3
}
},
computed:{
myExample(){
return id => this.examples.find(ex=>ex.exampleID===id)
}
}
rendering part will be like
<Task :example="myExample(id)"/>
In this way you no need to hardcode the value as 3 in the computed property.
来源:https://stackoverflow.com/questions/64790662/how-do-i-display-one-object-of-an-array-in-vue-js