簡體   English   中英

如何在 Vue.js 中將搜索查詢框合並到 api 調用中

[英]How to incorporate a search query box into api call in Vue.js

到目前為止,當我硬編碼藝術家姓名時,我可以在表格中獲取數據。 我想要的是我的搜索框鏈接到 api 調用,所以當我搜索藝術家時,這些結果會顯示出來,我是 Vue 的新手。 到目前為止,我已經創建了,我認為 api 調用需要類似於:

https://itunes.apple.com/search?term=${this.search}&entity=album

<template>
  <div class="jumbotron">
    <h1 class="display-4">{{title}}</h1>
    <p class="lead">{{intro}}</p>
    <hr class="my-4">
    <form class="col-lg-6 col-sm-12 mr-auto ml-auto">
      <input
        class="form-control form-control-lg mb-3"
        type="search"
        placeholder="Search"
        aria-label="Search"
      >
      <table class="table table-sm table-light table-bordered" v-if="result.length">
        <thead class="thead-dark">
          <tr class="col-8">
            <th scope="col">Name</th>
            <th scope="col">Artist</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(result, index) in result" :key="index">
            <td>{{result.collectionName}}</td>
            <td>{{result.artistName}}</td>
          </tr>
        </tbody>
      </table>
      <button
        class="btn btn-success btn-lg btn-block mb-3"
        type="submit"
        v-on:click="getData"
        v-if="result.length < 1"
      >Get data</button>
    </form>
  </div>
</template>

<script>
export default {
  name: "Hero",
  props: {
    navLink: String
  },
  data: function() {
    return {
      title: "Simple Search",
      intro: "This is a simple hero unit, a simple jumbotron-style.",
      subintro:
        "It uses utility classes for typography and spacing to space content out.",
      result: [],
      search: ""
    };
  },

  watch: {
    search: function(val) {
      if (!val) {
        this.result = [];
      }
    }
  },

  methods: {
    getData: function() {
      fetch(
        "https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=drake&entity=album"
      )
        .then(response => response.json())
        .then(data => {
          this.result = data.results;
          console.log(data);
        });
    }
  }
};
</script>

<style>
.jumbotron {
  margin-bottom: 0rem !important;
}

.table {
  width: 100% !important;
}
</style>

如您所見,我對藝術家“Drake”進行了硬編碼只是為了進行實驗,但是如何將其鏈接到輸入搜索?

這很容易。 讓我描述一下。

  1. 禁用表單。 form內的button會導致頁面重新加載,但您不需要它。
<!--<form class="col-lg-6 col-sm-12 mr-auto ml-auto">-->
    ... some useful code inside ...
<!--</form>-->
  1. 使用v-model將輸入字段與您的模型連接起來
<input
    ....
    aria-label="Search"
    v-model="search"
>
  1. 當組件將 url 創建為this.search時使用模型。 必須被動地提供數據。
fetch(
  `https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=${this.search}&entity=album`
)

您可以在文檔中了解更多關於連接形式和 vue 模型的信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM