【问题标题】:Vue / axios filter types of same type as single itemVue / axios过滤类型与单项相同的类型
【发布时间】:2018-08-15 14:08:12
【问题描述】:

我有一个应用程序,我想在其中显示项目列表。当您单击单个项目时,您会被发送到它的“页面”,其中会显示其信息。

这些项目有一个类型。

在单个项目信息下,我想显示所有具有相同类型的项目,从所有项目列表中过滤。但是我不知道在我的filterItems()-方法中返回什么。由于 axios 调用是使用 asyncData() 完成的,我无权访问 singleitem.type,是吗?

HTML:

<template>
    <div>
        <reusable-component v-for="item in singleitem" :key="item.id" />

        <reusable-component v-for="item in filterItems(type)" :key="item.id" />
    </div>
</template>

JS:

export default {
    data() {
        return {
            singleitem: [],
            allitems: []
        }
    },

    asyncData() {
        // Grab single item from ID supplied
        return axios.get(`https://url/to/GetItemById${params.id}`)
        .then((result) => {
            return { singleitem: result.data }
        })

        // Grab all items
        return axios.get('https://url/to/GetAllItems')
        .then((result) => {
            return { allitems: result.data }
        })
    },

    methods: {
        filterItems() {
            // Filter items from all items that has same type as the singleitem
            return allitems.filter(function(type) {
                // Help!
            })
        }
    }
}

【问题讨论】:

    标签: javascript vue.js vuejs2 axios nuxt.js


    【解决方案1】:

    我认为这是计算属性的用例 [https://vuejs.org/v2/guide/computed.html]

    可能是这样的:

    computed: {
      filterItems: function() {
        return this.allitems.filter(item => item.type != singleitem.type);
      }
    }
    

    所以每当数据发生变化时。 filterItems 得到(重新)计算。

    【讨论】:

    • 嗯,我使用methods 有两个原因。首先是 Vue 文档说的相反,computed 被缓存,而methods 每次都运行。第二个是因为computed 告诉我this.allitems.filter 不是函数:) 但是感谢您的输入。一旦我从后端获得正确的数据,我会报告
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2018-12-15
    相关资源
    最近更新 更多