Instant AJAX Search with Laravel and Vue
Instant AJAX Search with Laravel and Vue
Prologue: Official Package for the Real Work
Getting Started
Building the Back-End for the Feature
<?php // SearchController.php
public function search(Request $request)
{
$posts = Post::where('name', $request->keywords)->get();
return response()->json($posts);
}
Performing the Search with Vue
<template>
<div>
<input type="text" v-model="keywords">
<ul v-if="results.length > 0">
<li v-for="result in results" :key="result.id" v-text="result.name"></li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
keywords: null,
results: []
};
},
watch: {
keywords(after, before) {
this.fetch();
}
},
methods: {
fetch() {
axios.get('/api/search', { params: { keywords: this.keywords } })
.then(response => this.results = reponse.data)
.catch(error => {});
}
}
}
</script>
Debounce for the v-model
<input type="text" v-model.lazy="keywords" v-debounce="300">
Highlight the results
highlight(text) {
return text.replace(new RegExp(this.keywords, 'gi'), '<span class="highlighted">$&</span>');
}
Comments
Post a Comment