我有一個用 Axios 加載的陣列檔案,問題在于這個有一個包含影像和視頻的陣列,我無法更改它,我想要只有影像的陣列,有人可以幫忙嗎,謝謝你~
{
"data": [
{
"id": "01",
"media_type": "IMAGE",
"media_url": "https://...",
},
{
"id": "02",
"media_type": "VIDEO",
"media_url": "https://...",
},
{
"id": "02",
"media_type": "IMAGE",
"media_url": "https://...",
},
...
]
}
<div class="xx" v-for="event in events.data.slice(0, 6)" v-if="event.media_type == 'IMAGE'">
<img :src="event.media_url" :alt="event.caption">
</div>
data() {
return {
insta: "gram",
events: []
}
},
created() {
axios
.get('https:...')
.then(response => {
this.events = response.data
})
.catch(error => {
console.log('There is an error: ' error.response)
})
},
uj5u.com熱心網友回復:
您不應該真正混合v-for和v-if指令,因為它們令人困惑,在Vue2和Vue3 中都被官方勸阻,最重要的是,它們在 Vue2 和 Vue3 中具有不同的優先級。
如果您想處理過濾后的陣列(在這種情況下,您只需要影像),那么創建一個基于原始資料的計算道具。從您的代碼中不清楚您是否要先執行哪個操作:
- 獲取前 6 個條目
- 僅獲取影像
假設您想獲取所有影像,然后回傳前 6 張影像,那么這將起作用:
computed: {
filteredEvents() {
return this.events.data.filter(d => d.media_type === 'IMAGE').slice(0,6);
}
}
如果您想獲取任何 6 個第一個條目,然后按影像過濾它們,那么只需切換鏈接:
computed: {
filteredEvents() {
return this.events.data.slice(0,6).filter(d => d.media_type === 'IMAGE');
}
}
然后你可以在你的模板中使用它:
<div v-for="event in filteredEvents">
<img :src="event.media_url" :alt="如何在帶有陣列和 v-for 的 Vuejs 中使用條件?">
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407464.html
標籤:
