Suppose you have this list:
<template> <div> <h1>Avengers </h1> <ul> <li v-for="(hero, index) in heroes" :key="index"> {{hero}} </li> </ul> </div> </template> <script> export default { name: "App" data(){ heroes: ["Ironman", "Capitan America", "Hulk", "Thor", "Black Widow"] } } </script>
And then you wanted to add a search filter, so when you type in input field, it'll show matching heroes.
<template> <div> <h1>Avengers </h1> <input type="text" placeholder="Search Heroes" /> <ul> <li v-for="(hero, index) in heroes" :key="index"> {{hero}} </li> </ul> </div> </template> <script> export default { name: "App" data(){ heroes: ["Ironman", "Capitan America", "Hulk", "Thor", "Black Widow"] } } </script>
You can use computed properties for that.
But What exactly are Computed Properties?
Computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner.
Second thing is computed properties are cached based on their dependencies means it'll only re-evaluate when some of its dependencies changed.
In code below, I have created a computed property heroList
and have added term
as a dependency, so when term
is changed, heroList will be re-evaluated and rendered.
That means, When you type in input field, it'll change term
value and re-render the list.
Type in input -> term value change -> heroList re-evaluated -> render heroList
<template> <div> <h1>Avengers </h1> <input type="text" placeholder="Search Hero's" v-model="term"/> <ul> <li v-for="(hero, index) in heroList" :key="index"> {{hero}} </li> </ul> </div> </template> <script> export default { name: "App" data(){ heroes: ["Ironman", "Capitan America", "Hulk", "Thor", "Black Widow"], term : "" }, computed: { // filtered list of heroes heroList(){ return this.heroes.filter(hero => { return hero.indexOf(this.term) !== -1 }) } } } </script>
Thanks for reading.
Top comments (0)