Skip to content

Instantly share code, notes, and snippets.

@andberry
Last active July 15, 2022 18:00
Show Gist options
  • Save andberry/7aebd803b4424d03f4ac266b688820d9 to your computer and use it in GitHub Desktop.
Save andberry/7aebd803b4424d03f4ac266b688820d9 to your computer and use it in GitHub Desktop.
In page search with Vue.js
# HTML
[...]
<div id="searchapp">
<div class="search" ref="searchEl">
<input id="search__input" type="text" name="search" placeholder="Type for search (min 3 chars)" v-model="searchString">
<transition name="fade">
<div v-if="searchResults.length > 0 && searchResultsVisible === true" class="search__results">
<ul>
<li v-for="(doc, k) in searchResults" :key="k">
{{ doc.text }}
</li>
</ul>
</div>
</transition>
</div>
</div>
[...]
<ul class="list">
<li class="list__item">
[...]
<div class="list__item__description">Lorem Ipsum...</div>
[...]
</li>
</ul>
[...]
# CSS
[...]
.fade-enter-active, .fade-leave-active {
transition: opacity 250ms;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
[...]
# JavaScript
var searchApp = new Vue({
el: '#searchapp',
data: {
documents: [],
searchString: '',
searchResultsVisible: true
},
mounted: function () {
docsEls = document.querySelectorAll('.list__item');
for (const item of Array.from(docsEls)) {
this.documents.push({
text: item.querySelector('.list__item__description').innerHTML
});
}
// Usability improvement: click on body hides search results
document.documentElement.addEventListener('click', this.handleClickOnBody);
// Usability improvement: Esc key on keyboard hides search results
document.addEventListener('keyup', this.handleKeyUp);
},
computed: {
activeSearchString: function () {
return (this.searchString.length >= 3) ? this.searchString : '';
},
searchResults: function () {
if ( this.activeSearchString !== '' ) {
return this.documents.filter( d => d.text.toLowerCase().includes(this.activeSearchString.toLowerCase()) == true );
} else {
return []
}
}
},
methods: {
handleClickOnBody: function (e) {
const target = e.target;
const searchEl = this.$refs.searchEl;
if (target !== searchEl && !searchEl.contains(target)) {
this.searchResultsVisible = false;
} else {
this.searchResultsVisible = true;
}
},
handleKeyUp: function (e) {
if ( e.key === 'Escape' ) {
this.searchResultsVisible = false;
}
}
}
});
@innocent-maina
Copy link

This is awesome !!!
Just what I was looking for

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment