[英]How do I display one object of an array in Vue.JS
Let's say I have this list of objects in Vue.JS假设我在 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现在假设我想在我之前创建的元素中显示 exampleID 为 3 的对象
<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)我想显示对象中的所有内容(ID 和文本)
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>
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 :您不应该在同一个元素中使用
v-if
和v-for
,在这种情况下,我建议使用仅返回所需示例的计算属性:
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"/>
Another efficient way of doing it without v-for is另一种没有 v-for 的有效方法是
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.通过这种方式,您无需将计算属性中的值硬编码为 3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.