首页 > 解决方案 > 使用 v-for 过滤数据库中的数据

问题描述

在这里,我尝试在脚本(vue js)中制作一个 const 数据。

data() {
    return {
    event: [],
    items: [
      [id: '1', month:'January', date:'01'],
      [id: '2', month:'February', date:'03'],
    ]}
}
filter(val) {
  let items = this.items;
  let filter = items.filter(el => el.month === val);
  this.event = filter;
}

并在我的v-for

<h1 v-for="(item, id) in event" v-bind:key="id"></h1>
<p>{{ items.month }}</p>

它循环从空事件数组中过滤的项目。

由于我的 const 数据太多。我尝试创建一个 API。

这就是我从数据库中获取数据的方式。

data() {
  return {
    Items: [],
  }
}

getHoliday(){
    getTest.getHoliday()
            .then(response =>{
                this.Items = response.data;
            })
    },

并使用循环遍历它v-for

<h1 v-for="(Item, id) in Items" v-bind:key="id"></h1>
<p>{{ Item.month }}</p>

从这里开始,我只知道如何通过 mustache 调用具体的数据。我不能做我在使用 const 数据时使用的过滤器。

标签: vuejs2laravel-5.4

解决方案


如果我正确理解了这个问题,您可以通过计算属性过滤来自后端的数据。

computed: {
    filteredItems() {
        return this.Items.filter((item) => {...});
    },
},

在您的模板中,您可以迭代这个新属性

<h1 v-for="(Item, id) in filteredItems" v-bind:key="id">{{ Item.month }}</h1>

推荐阅读