How do I display one object of an array in Vue.JS

限于喜欢 提交于 2021-01-29 08:07:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!