How do I reset a my response to NULL, as it is in my data upon the clearing/deleting of the query in my search bar?
I've vaguely achieved this with v-show and a query length, but I know its not really correct because it's hiding the results, not actually clearing them from the DOM. I also tried tying an ELSE statement to the query method with no luck.
<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)
})
}
}
}
};
I need my search input to remove the response by resetting it to NULL once the input has been cleared by the visitor. Presently if you clear the input, the results disappear which is great but if you type again, the results just reappear. So they are hidden, not removed. I believe I need a function, possibly via computed, to set the response in data back to null upon the clearing of the input.
You could attach an input
event handler to your input
element and inside it you'll check the length of the query
string. If it's zero, then set response
to null
.
<input type="search" placeholder="Search Repositories Ex. Hello
World" v-model="query" @input="onQueryChange" />
The onQueryChange
function should be under methods
instead of computed
since it's not returning any derived data.
methods: {
onQueryChange(event) {
// can be this.query.length === 0 as well
if(event.target.value.trim().length === 0) {
this.response = null;
}
}
}