【问题标题】:How to use condition with Vuejs with array and v-for?如何在带有数组和 v-for 的 Vuejs 中使用条件?
【发布时间】:2022-01-10 09:29:13
【问题描述】:

我有一个用 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)
        })
},

【问题讨论】:

    标签: arrays vue.js axios v-for


    【解决方案1】:

    您真的不应该混合使用 v-forv-if 指令,因为它们令人困惑,官方不鼓励在 Vue2Vue3 中使用,最重要的是,它们在 have different precedence in Vue2 vs 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 class="xx" v-for="event in filteredEvents">
      <img :src="event.media_url" :alt="event.caption">
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      相关资源
      最近更新 更多