【问题标题】:Reset response to null after search input is cleared Vue.js清除搜索输入后将响应重置为 null Vue.js
【发布时间】:2019-06-10 15:19:52
【问题描述】:

如何将我的响应重置为 NULL,因为它在我的搜索栏中清除/删除查询后的数据中?

我已经通过 v-show 和查询长度模糊地实现了这一点,但我知道它并不真正正确,因为它隐藏了结果,而不是真正从 DOM 中清除它们。我还尝试将 ELSE 语句绑定到查询方法,但没有成功。

<div class="searchBarContainer">
   <div class="search">
      <div class="searchBar">
       <form v-on:submit="queryGitHub(query)">
        <input type="search" placeholder="Search Repositories Ex. Hello 
 World" v-model="query" />
      <button type="submit" v-on:click="isHidden = 
 !isHidden">Search</button>
    </form>
  </div>

  <div class="results" id="results" v-if="response" v-show="query.length = 
 0">
    <div class="notFound" v-if="response.length == 0">
      <p>Sorry buddy, try another search!</p>
    </div>

    <div class="resultsHeadings" v-if="response.length >= 1">
      <p>Name</p>
      <p>Language</p>
    </div>

    <div class="items" v-if="response.length >= 1">
      <div class="item" v-for="(item, index) in response, filteredList" 
 v-bind:id="item.id" :key="index"> 
          <p>{{item.name}}</p>
          <p>{{item.language}}</p>

          <div class="expand">
            <a @click="pushItem(index)">
              <div class="itemButton">
                <button v-on:click="addFave(item.id, item.forks)">Add to 
 Favorites</button>
              </div>
          </div>
      </div>
    </div>
   </div>
  </div>
 </div>


 <script>

 export default{
  data () {
    return {
     query:'',
     response: null,
     items: [],
     faves: [],
     activeItems: [],
   }
  },
  methods: {
    queryGitHub(q) {
    if (q.length >= 1){
    fetch('https://api.github.com/search/repositories?q=' + q)
    .then((j) => {
      return j.json();
    })
    .then ((r) => {
    console.log(r);
    //this.response = r.items;

    this.response = r.items.slice(0, 15)
      })
    }
    }
    }
  };

一旦访问者清除了输入,我需要我的搜索输入通过将其重置为 NULL 来删除响应。目前,如果您清除输入,结果会消失,这很好,但如果您再次输入,结果就会重新出现。所以它们是隐藏的,而不是删除的。我相信我需要一个函数,可能通过计算,在清除输入时将数据中的响应设置回 null。

【问题讨论】:

  • 不确定您在此处尝试达到的行为是什么,您的意思是当用户删除搜索输入时,您的response 再次设置为null

标签: javascript vue.js conditional-rendering


【解决方案1】:

您可以将input 事件处理程序附加到您的input 元素,并在其中检查query 字符串的长度。如果为零,则将response 设置为null

<input type="search" placeholder="Search Repositories Ex. Hello 
 World" v-model="query" @input="onQueryChange" />

onQueryChange 函数应该在 methods 而不是 computed 下,因为它不返回任何派生数据。

methods: {
  onQueryChange(event) {

    // can be this.query.length === 0 as well
    if(event.target.value.trim().length === 0) {
      this.response = null;
    }

  }
}

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2017-01-18
    • 2019-03-24
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多