无法在 VueJS 上从 API 过滤数组

Unable to Filter Array from API on VueJS

我正在开发 Nativescript-Vue 应用程序,我正在尝试解决这个问题。

情况

我从 API 接收数据。以下是我从 api

收到的数据结构
{
"count": 9,
"results": [
    {
        "id": 1,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",            
        "gender": "male",
        "age": 32,
        "status": "active",

    },
    {
        "id": 3,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",            
        "gender": "male",
        "age": 32,
        "status": "active",

    },
    {
        "id": 4,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",
        "age": 34,
        "status": "inactive",

    },
    {
        "id": 6,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",
        "age": 65,
       "status": "inactive",
    },
    {
        "id": 2,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",
        "age": 19,
        "status": "pending",

    },

]

下面是我的vue代码。

 export default {
data() {

    return{
        allData:[],
        total:[],
        active:[],
        inactive:[],
        pending:[]       

       }
},
mounted() {
   axios({ method: "GET", "url": "https://api.url" }).then(
       response =>
       {            

             this.allData = response.data.results,
             this.total = response.data.count               

         }, error => {
            console.error(error);
        }
   )       
},

computed:{
        active(){
            return this.allData.filter((status)=>{
                return this.allData.status.match("active");
                 })
            }

        },

  }

我的objective是显示应用中活跃、不活跃和待定状态的记录数。我正在使用此代码段来执行此操作。

<Label class="numbers" :text="active.count" width="200" height="50" />

谁能告诉我我哪里失败了。

提前致谢。 Ashish A.

您的 active 过滤器没有按照您的实际意图执行。

如果将其更改为以下内容,它应该可以正确过滤 - active 将 return 一组活动项目。如果您只关心它们的数量,您可以在过滤器之后链接 .length,它会 return 一些活动项目。

computed: {
  active() {
    return this.allData.filter((item) => item.status === "active");
  }
}

有关 filter 方法的详细信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

首先更新你的计算 属性 如:

computed: {
    active() {
      return this.allData.filter(d => d.status === 'active')
    }
  },
}

因为,使用 this.allData.status 不正确,因为 statusallData 数组中对象的 属性。 this.allData[0].status 会起作用,但在 filter() 方法中不需要,因为我们使用 d 变量在过滤器中获取每个对象。

然后像这样更新您的模板:

<Label class="numbers" :text="active.length" width="200" height="50" />

请注意active这里是一个数组,数组没有任何count 属性,请使用length来获取活动数据的计数。