如何在 Vue.JS 中显示数组的一个对象 [英] How do I display one object of an array in Vue.JS
本文介绍了如何在 Vue.JS 中显示数组的一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在 Vue.JS 中有这个对象列表
data(){返回{例子: [{示例ID:5,示例文本:'foo'},{示例ID:3,示例文本:'酒吧'}]}}
现在假设我想在我之前创建的元素中显示 exampleID 为 3 的对象
<任务v-for=示例中的示例";:key="example.exampleID";:example="示例"/>
我想显示对象中的所有内容(ID 和文本)
任务组件:
<div class="锻炼"><div class="exercise-id"><h1>ID 号:{{example.exampleID }}</h1>
<div class="exercise-task"><h2>{{example.exampleText}}</h2>
模板><脚本>导出默认{name: '任务',道具:['例子']}
解决方案
你不应该在同一个元素中使用 v-if
和 v-for
,在这个如果我建议使用仅返回所需示例的计算属性:
data(){返回{例子: [{示例ID:5,示例文本:'foo'},{示例ID:3,示例文本:'酒吧'}]}},计算:{我的例子(){返回 this.examples.find(ex=>ex.exampleID===3)}}
然后将其渲染为:
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>
解决方案
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"/>
这篇关于如何在 Vue.JS 中显示数组的一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!