簡體   English   中英

如何在 Vue.JS 中顯示數組的一個對象

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

假設我在 Vue.JS 中有這個對象列表

data () {
return{
  examples: [
    {
      exampleID: 5,
      exampleText: 'foo'
    },
    {
      exampleID: 3,
      exampleText: 'bar'
    }
  ]
}
}

現在假設我想在我之前創建的元素中顯示 exampleID 為 3 的對象

   <Task 
  v-for="example in examples"
  :key="example.exampleID"
  :example="example"
/>

我想顯示對象中的所有內容(ID 和文本)

任務組件:

<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>

您不應該在同一個元素中使用v-ifv-for ,在這種情況下,我建議使用僅返回所需示例的計算屬性:

data () {
return{
  examples: [
    {
      exampleID: 5,
      exampleText: 'foo'
    },
    {
      exampleID: 3,
      exampleText: 'bar'
    }
  ]
}
},
computed:{
    myExample(){
       return this.examples.find(ex=>ex.exampleID===3)
    }
}

然后將其渲染為:

  <Task   :example="myExample"/>

另一種沒有 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)
    }
}

渲染部分會像

<Task :example="myExample(id)"/>

通過這種方式,您無需將計算屬性中的值硬編碼為 3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM