I have the vue component below:
<template>
<div class="container">
<div class="row">
<div class="col-md-4" v-for="product in products" :key="product.id">
<div class="card mb-4">
<!-- <img :src="product.image" class="card-img-top" alt="..."> -->
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.description }}</p>
<a href="#" class="btn btn-primary">Buy</a>
</div>
</div>
</div>
</div>
<nav>
<ul class="pagination">
<li class="page-item" :class="{ 'disabled': !links.prev }">
<a class="page-link" @click.prevent="getProducts(links.prev)" href="#">Previous</a>
</li>
<li class="page-item">
<span class="page-link">{{ meta.current_page }}/{{ meta.last_page }}</span>
</li>
<li class="page-item" :class="{ 'disabled': !links.next }">
<a class="page-link" @click.prevent="getProducts(links.next)" href="#">Next</a>
</li>
</ul>
</nav>
</div>
</template>
<script>
export default {
data(){
return {
products: [],
meta: {},
links: {}
}
},
methods: {
getProducts(url = '/api/products') {
axios.get(url)
.then(response => {
this.products = response.data.data;
this.meta = response.data.meta;
this.links = response.data.links;
});
},
},
mounted(){
this.getProducts();
},
}
</script>
I have a simple resource API made with Laravel. When you load up the page, it lists the products from the database, and you can also paginate it.
How could I put a filtering option into it? Like a simple text input, and when you write something in it, the data is filtered?
I’ve tried binding a variable to the input and passing it to the getProducts method, but it didn’t work.
I’m very new to vue3 and a bit familiar with Laravel, so bear with me if possible…
2
Answers
What you need to do is just that: filter the data, and the best way to do this with Vue.js is to use a computed property.
For instance, if you had a bunch of "product" data held in an array, data that had, for instance, id, name and description properties, and you also had a filterText field that held the text that you would use for filtering, then you could create a computed property, say called
filteredProducts
that returned this array filtered by the text of interest. You could even make this same computed property filter just the property name or both its name and description, if desired, something like so (using composition API):You could then use this computed property just as you would any other property in your program.
A complete example could look like so:
store.js
App.vue
A runnable example can be found on the Vue SFC Playground
The simplest thing of course you can do is to filter by the model value (whatever value in your input). That is to say that your computed will react to each change of your input value and return computed result.
The way it works is that computed basically re-calculates whenever its reactive dependency (input) is changed