123movies-seo/resources/js/components/Search.js

67 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-08-24 23:08:42 +03:00
export default () => ({
search: false,
searchValue: '',
isLoading: true,
results: '',
init() {
// this.$el.classList.remove('hidden');
// this.openMenu();
// this.open();
},
closeSearch() {
this.searchValue = '';
},
isSearchOpen() {
return this.search === true;
},
isMenuOpen() {
return this.menu === true;
},
showOverlay() {
return this.search || this.menu
},
shouldSearch() {
return this.searchValue.length >= 2;
},
searching(fetch = true) {
if(fetch){
this.isLoading = true;
this.$refs.results.classList.add('opacity-0')
} else {
this.isLoading = false;
this.$refs.results.classList.remove('opacity-0')
}
},
fetchResults(query) {
// console.log(query);
if (this.shouldSearch) {
this.searching();
fetch('/api/search', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({query: this.searchValue})
}).then(res => {
if (res.ok) {
return res.json();
}
throw new Error('Something went wrong');
}).then(data => {
this.results = data.html.length ? data.html : `<span class='w-full p-1.5 group overflow-hidden bg-gray-800 hover:bg-gray-700 h-20 flex items-center justify-center font-semibold'>No Result Found</span>`
setTimeout(this.searching(false), 2000)
})
.catch( (error) => {
console.log(error);
});
}
}
});