javascript - 如何使用 Vue js 从 API 数据创建搜索过滤器?

标签 javascript laravel api vue.js single-page-application

我正在从 Star Wars API 获取数据,更具体地说是人员数据,并且它正在工作。我想创建一个搜索过滤器功能,当我开始输入时,只显示带有这些字母的名称。 这是我用于获取 StarWarsPeopleComponent.vue 文件中的数据的代码:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <input type='text' v-model="search" placeholder='Search people...'/><br>

                {{ getAllStarWarsPeople() }}

                <ul>
                    <li v-for="person in people.results">
                        {{ person.name }}
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>

    export default {

        name: "StarWarsPeopleComponent",

        data() {
            return {
                people: [],
                search: ''
            }
        },

        mounted() {
            console.log('Component mounted.')
        },

        methods:{

            getAllStarWarsPeople() {

                fetch("https://swapi.co/api/people/")
                    .then(response=>response.json())
                    .then(data=>{
                        this.people=data;
                    })

            }

        }
    }
</script>

请注意我如何使用 people.results 访问 v-for 中的数据。

这是使用我创建的计算函数更新的组件,但现在数据未显示,并且出现此错误:

[Vue warn]: Error in render: "TypeError: this.people.filter is not a function".

我对 Vue js 还很陌生,我不知道这意味着什么或如何修复它。 有人可以帮忙吗?

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <input type='text' v-model="search" placeholder='Search people...'/><br>

                {{ getAllStarWarsPeople() }}

                <ul>
                    <li v-for="person in filteredPeople">
                        {{ person.name }}
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>

    export default {

        name: "StarWarsPeopleComponent",

        data() {
            return {
                people: [],
                search: ''
            }
        },
        mounted() {
            console.log('Component mounted.')
        },
        methods:{

            getAllStarWarsPeople() {

                fetch("https://swapi.co/api/people/")
                    .then(response=>response.json())
                    .then(data=>{
                        this.people=data;
                    })

            }

        },
        computed: {
            filteredPeople: function() {
                return this.people.filter((person) => {
                   return person.name.match(this.search);
                });
            }
        }
    }
</script>

最佳答案

在组件加载时使用“created()”调用 getAllStarWarsPeople()。

在输入字段中添加 getAllStarWarsPeople 作为“@keyup”。

试试这个:

<template>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <input
          type="text"
          v-model.trim="search"
          placeholder="Search people..."
          @keyup="getAllStarWarsPeople"
        /><br />
        <ul>
          <li v-for="person in people" :key="person.id">
            {{ person.name }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "StarWarsPeopleComponent",

  data() {
    return {
      people: [],
      search: ""
    };
  },

  mounted() {
    console.log("Component mounted.");
  },

  methods: {
    getAllStarWarsPeople() {
      fetch("https://swapi.dev/api/people/")
        .then(response => response.json())
        .then(res => {
          if (this.search) {
            this.people = res.results.filter(people =>
              people.name.toLowerCase().includes(this.search.toLowerCase())
            );
          } else {
            this.people = res.results;
          }
        });
    }
  },
  created() {
    this.getAllStarWarsPeople();
  }
};
</script>

这里是 JsFiddle:

new Vue({
  el: "#app",
  data: {
    people: [],
    search: ""
  },
  methods: {
    getAllStarWarsPeople() {
      fetch("https://swapi.dev/api/people/")
        .then(response => response.json())
        .then(res => {
          if (this.search) {
            this.people = res.results.filter(people =>
              people.name.toLowerCase().includes(this.search.toLowerCase())
            );
          } else {
            this.people = res.results;
          }
        });
    }
  },
  created() {
    this.getAllStarWarsPeople();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
  <div id="app">
    <input
      type="text"
      v-model.trim="search"
      placeholder="Search people..."
      @keyup="getAllStarWarsPeople"
    /><br />
    <ul>
      <li v-for="person in people" :key="person.id">
        {{ person.name }}
      </li>
    </ul>
</div>

关于javascript - 如何使用 Vue js 从 API 数据创建搜索过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59761889/

相关文章:

mysql - Laravel 编写一个查询来查找是否在日期启用了访问

javascript - 我如何确定用户是否发过推文[我的意思是发推未点击推文按钮]?

php - 如何在 Laravel 中手动捕获错误异常

javascript - Mongo - 多个引用对象数组中的值的总和

javascript - 使 2 列不同

php - 在 Laravel 中使用条码编号作为主键

php - Laravel - 尝试获取非对象形式错误的属性

javascript - 制作Ajax Handler,需要问一些安全问题

javascript - 按住鼠标按钮且光标不在视口(viewport)外时如何检测鼠标离开?

javascript - 圆 Angular