can i write a filter search code with just data and methods function?
i try do this :
var fil = new Vue ({
el: '#app',
data: {
search: '',
proL: ['css', 'c++', 'cs#'],
},
methods: {
filter: function(){
var search_key = this.search.val();
this.proL.filter(function(){
this.proL.toggle(this.proL.text().indexOf(search_key) > -1);
});
}
}
});
and this is the html code
<div id="app">
<div >
<input @keyup="filter()" type="text" v-model="search" placeholder="Search title.."/>
</div>
<div id="pro">
<h4 v-for="item in proL">{{item}}</h4>
</div>
</div>
๐ ๐
Try to use a computed property to define the filtered items and use an arrow function as filter function callback in order to get access to this:
new Vue({
el: '#demo',
data: {
search: '',
proL: ['css', 'c++', 'cs#'],
},
computed: {
filtered(){
return this.proL.filter(e => e.toLowerCase().includes(this.search.toLowerCase()))
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div >
<input type="text" v-model="search" placeholder="Search title.."/>
</div>
<div id="pro">
<h4 v-for="item in filtered">{{item}}</h4>
</div>
</div>
A better approach would be using computed handler
new Vue({
el: '#demo',
data: {
search: '',
proL: ['css', 'c++', 'cs#'],
},
computed: {
filteredProL(){
if(this.search === '') return this.proL; // If search input is empty then display all items
else return this.proL.filter(e => e.toLowerCase().indexOf(this.search) > -1) // Working logic
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div >
<input type="text" v-model="search" placeholder="Search title.."/>
</div>
<div id="pro">
<h4 v-for="item in filteredProl">{{item}}</h4>
</div>
</div>