在空的输入字段上显示错误消息,然后在填充输入字段时隐藏消息

时间:2019-06-16 23:54:20

标签: javascript vue.js vue-component

在我的Vue.js应用中,我有一个搜索输入,此刻如果搜索为空,它会显示一条错误消息,这很好,但是当用户开始向搜索中添加输入时,我想隐藏它领域。到目前为止,我的组件代码如下,其中显示了模板和脚本区域。

<template>
  <div class="jumbotron">
    <h1 class="display-4">{{title}}</h1>
    <p class="lead">{{intro}}</p>
    <hr class="my-4">
    <p v-if="errors.length">
      <b>Please correct the following error(s):</b>
    </p>
    <p v-for="(error, index ) in errors" :key="index">{{ error }}</p>
    <input
      class="form-control form-control-lg mb-3"
      type="search"
      placeholder="Search"
      aria-label="Search"
      v-model="search"
      required
    >

    <div class="loading" v-if="loading"></div>

    <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>
  </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: [],
      errors: [],
      search: "",
      loading: ""
    };
  },

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

  methods: {
    getData: function() {
      this.loading = true;
      fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
        .then(response => response.json())
        .then(data => {
          this.result = data.results;
          this.loading = false;
          console.log(data);
        });
      if (this.search) return true;
      this.errors = [];
      if (!this.search) this.errors.push("Enter search field.");
    }
  }
};
</script>

任何想法都很棒,我需要将其添加到v-if语句中还是在脚本标签中?

1 个答案:

答案 0 :(得分:0)

您应注意search属性,如果未输入search,则更新错误数组:

methods: {
  getData: function() {
    this.loading = true;
    fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
      .then(response => response.json())
      .then(data => {
        this.result = data.results;
        this.loading = false;
        console.log(data);
      });
  }
},
watch: {
  search: function(val) {
    if (!val) {
      this.result = [];
      this.errors = [];
      this.errors.push("Enter search field.");
    }
  }
}