【问题标题】:get request with axios and vujes在 vuejs 中使用 axios 获取请求
【发布时间】:2021-11-02 08:56:22
【问题描述】:

大家下午好,

如何每次在我的应用上使用搜索按钮发送Get 请求?

我不想只从 API 下载整个 JSON 搜索结果?

非常感谢。

那是我的搜索栏:


     <div id="app">
        <div class="search-wrapper">
        <input type="text" 
               class="search-bar" 
               v-model="search"
               placeholder="Search in the titles"/>
          
      </div>

这是我拥有的 axios 部分:


      axios
        .get(
          `https://zbeta2.mykuwaitnet.net/backend/en/api/v2/media-center/press-release/?page_size=61&type=5`
        )
        .then((response) => {
          this.items = response.data.results;
        });

【问题讨论】:

  • 如果 api 有搜索参数,请使用它,否则按您的搜索字段过滤结果
  • "我不想从 api 下载整个 json,只下载搜索结果?" - 这不是 api 的工作方式。您有一个带有大量分页数据的 api 端点。如果它没有提供一个端点来搜索它,那么您将无能为力,因为执行数百个请求来下载整个数据集是完全不合理的。您需要与后端开发人员合作。

标签: vue.js axios


【解决方案1】:

第一步:创建HTML模板

<div class="search-wrapper">
  <form>
    <input
      type="search"
      @input="searchByTitle($event.target.value)"
      class="search-bar"
      v-model="search"
      placeholder="Search by title"
    />
  </form>
</div>

第 2 步: 添加search by title method

searchByTitle(value) {
  clearTimeout(this.debounce);
  this.debounce = setTimeout(() => {
    if (value.length >= 3) {
      this.params = `q=${value}`;
      this.loadPressRelease();
    }
  }, 600);
},

当有 3 个或超过 3 个字符时,我们必须拨打 REST API 电话,并在我们停止输入后添加 debounce,那么只有我们在拨打 REST API 电话

第 3 步:添加watch 用于清除搜索文本时

watch: {
  search(newVal, oldVal) {
    if (oldVal && !newVal) {
      console.log("morning has broken...");
    }
    if (!newVal) {
      this.clearSearch();
    }
  },
},

第 4 步:添加了搜索栏 css 样式

.search-bar {
  border: 1px solid #ccc;
  outline: 0;
  border-radius: 10px;
  width: 50%;
  margin-left: 10px;
  padding: 0.5rem;
}
.search-bar:focus {
  box-shadow: 0 0 15px 5px #b0e0ee;
  border: 2px solid #bebede;
}
.search-box:not(:valid) ~ .close-icon {
  display: none;
}

DEMO

【讨论】: