首页 > 解决方案 > 实时搜索组件

问题描述

我从外部 API 链接获取我的数据,我想过滤它们 - 实时搜索,所以当我输入一个字母时,包含该字母的结果将被过滤。

现在我无法做到这一点,当我点击我的输入时,我只会打印出所有结果,而当我试图过滤它们时什么也没有发生。

这是我在脚本中的逻辑:

data() {
    return {
      result: "",
      modal: false,
      results: [],
      filteredResults: [],
    };
  },
  mounted() {
    axios
      .get("secretDataURL")
      .then((response) => {
        this.filteredResults = response.data;
      })
      .catch((error) => (this.filteredResults = console.log(error)))
      .finally(() => console.log("Data successfully loaded"));
  },
  methods: {
    filterResults() {
      if (this.result.lenght == 0) {
        this.filteredResults = this.results;
      }
      this.filteredResults = this.results.filter((result) => {
        return result.toLowerCase().startsWith(this.result.toLowerCase());
      });
    },
    setResult(result) {
      this.result = result;
      this.modal = false;
    },
  },
  watch: {
    state() {
      this.filterResults();
    },
  }

还有我的模板

<div @click="modal = false"></div>
    <input
      type="text"
      v-model="result"
      autocomplete="off"
      @input="filterResults"
      @focus="modal = true"
    />
    <div v-if="filteredResults && modal">
      <ul>
        <li
          v-for="(filteredResult, index) in filteredResults"
          :key="index"
          @click="setResult(filteredResult)"
        >
          {{ filteredResult.name }}
        </li>
      </ul>
    </div>

我怎样才能使它工作,我的逻辑在哪里失败?

标签: vue.jsfiltering

解决方案


你在 hook 中获取数据mounted。然后丢了。

在此处输入图像描述


更改this.filteredResults = response.data;this.results = response.data;


推荐阅读