【问题标题】:TypeError: this.results.filter is not a function in searchbox VuejsTypeError:this.results.filter 不是 Vuejs 搜索框中的函数
【发布时间】:2020-01-13 20:13:16
【问题描述】:

我一直在努力在 VueJS 2.0 中实现搜索功能。

我正在尝试复制我在Stackoverflow 中获得的这段代码,但无法实现它。

我不知道我在哪里做错了。

结果是一个存储json数据的对象。

    <template>
  <section>
    <b-form-input v-model="searchQuery" placeholder="Search user by full name"></b-form-input>
    <div v-for="result in filteredResources" :key="result.id">
      <td>{{result.LONG_D}}</td>
    </div>
  </section>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      searchQuery: "",
      results: {},
      search: ""
    };
  },
  mounted() {
    this.getDiseases();
  },
  methods: {
    getDiseases: function() {
      axios
        .get("http://localhost:9000/api/diseases/")
        .then(response => (this.results = response.data))
        .catch(error => console.log(error));
    }
  },
  computed: {
    /* Search Bar */
    filteredResources() {
      if (this.searchQuery) {
        return this.results.filter((item) => {
          return item.title.startsWith(this.searchQuery);
        });
      } else {
        return this.results;
      }
    }
  }
};
</script>

这是错误

TypeError: this.results.filter 不是函数

这是将存储在 result:{} 中的 json

【问题讨论】:

  • 你不能在一个对象上调用.filter
  • 那我该怎么办?
  • Object.keys(this.results).filter((key) =&gt; this.results[key].title.startsWith(this.searchQuery)) 可能会起作用。
  • 虽然不行
  • response.data 是一个数组吗?如果是这样,请将您的results 数据属性初始化为相同类型,即results: []

标签: javascript vue.js vuejs2


【解决方案1】:

我建议直接使用 AJAX 响应中的 results 数组。

例如

data: () => ({
  searchQuery: '',
  results: []
}),
async created () {
  let { data } = await axios.get("http://localhost:9000/api/diseases/")
  this.results = data.results
},
computed: {
  filteredResources() {
    let normalizedQuery = this.searchQuery.trim().toLowerCase()
    if (normalizedQuery.length) {
      return this.results.filter(({ LONG_D }) => 
          LONG_D.toLowerCase().startsWith(normalizedQuery))
    }
    return this.results
  }
}

你还应该修复你的模板

<div v-for="result in filteredResources">
  <p>{{result.LONG_D}}</p>
</div>

【讨论】:

  • 嗨菲尔,为什么要使用异步?我不知道 asnyc 和你写的所有代码。
  • @Vin 因为它更短而且我讨厌滚动?。同axios.get(...).then(response =&gt; (this.results = response.data.results))
猜你喜欢
  • 1970-01-01
  • 2020-02-09
  • 2017-06-23
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 2021-09-24
相关资源
最近更新 更多