【问题标题】:Apply filter to API response - vue.js将过滤器应用于 API 响应 - vue.js
【发布时间】:2018-08-02 08:02:07
【问题描述】:

我有这个从 API 获取数据的方法,它会向我发送许多家具的信息:

loadPieces() {
        this.isLoading = true;

        axios.get(this.galleryRoute)
            .then(r => {
                this.gallery = r.data;
                this.isLoading = false;
            })
            .catch(error => {
                this.$nextTick(() => this.loadPieces());
            });

        console.log(this.galleryRoute);
    },

这是我得到的响应的一部分,只代表一个部分:

[[{"id":266,"name":" Tray 7x45x32, white stained ash","thumbnail":{"width":840,"height":840,"urls":{"raw":"http:\/\/localhost:8888\/storage\/9c\/9d\/9c9dadc6-15a2-11e8-a80a-5eaddf2d1b4a.jpeg","small":"http:\/\/localhost:8888\/storage\/9c\/9d\/9c9dadc6-15a2-11e8-a80a-5eaddf2d1b4a@140.jpeg","medium":"http:\/\/localhost:8888\/storage\/9c\/9d\/9c9dadc6-15a2-11e8-a80a-5eaddf2d1b4a@420.jpeg"}}},

现在我想创建一个过滤器,以便我可以使用它的 id 从 JSON 对象中获取特定的片段。我已经尝试过搜索,但到目前为止我不知道该怎么做。

提前致谢!

【问题讨论】:

标签: vue.js axios


【解决方案1】:

添加一个计算属性,将过滤器应用于this.gallery

computed: {
  filteredGallery() {
    if (!this.gallery) return []; // handle gallery being unset in whatever way

    return this.gallery.filter(picture => 
      // some reason to show picture
    );
  }
}

我假设 gallery 是一个数组,但如果它是一个对象,您可以对其应用类似的技术,例如使用Object.keys(this.gallery).

然后在您的模板中,使用filteredGallery 而不是gallery

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 2019-03-09
    • 2012-12-07
    相关资源
    最近更新 更多