Discussion
Discussion copied to clipboard
Get count for filterBy
Is it possible when using filterBy to get the count of results? I would like to display "no results found". Thanks!
You can create a "side effect filter" at the end of the filter chain:
filters: {
count: function (arr) {
// record length
this.$set('filteredLength', arr.length)
// return it intact
return arr
}
}
Thanks for your reply! I'm a little confused with what you mean by "side effect filter". Do I still need to have a custom filter to do this or can I use the built in 'filterBy' on a model? I am not using any kind of custom filter now, just filtering off the model.
<input type="text" v-model="q">
<ul>
<li v-repeat="result: results | filterBy q">{{ result.title }}</li>
</ul>
Thanks for taking the time to help!
Ok I think I figured it out. I needed to do this:
<input type="text" v-model="q">
<ul>
<li v-repeat="result: results | filterBy q | count">{{ result.title }}</li>
</ul>
It works now. Thanks!
Thanks for the solution ! :+1:
how about just
'count': function(collection) {
return collection.length;
}
Is there a benefit to saving it to a property if you don't use it later ?
The filter absolutely needs to return an array in order to not break functionality. That's what Evan meant by "side effect". It's supposed to filter out array elements, but in fact it just writes an additional attribute and returns the 'filtered' array unchanged.
I found a other solution, I dont know if is the right way.
Vue.filter('count', function (arr) {
var res = arr.length
return res
})
<input type="text" v-model="q">
<p>{{ result | filterBy q | count }}</p>
It's work good for me.
Hey I am kinda new to Vue. I have question on same line.
I am looking for a way to show the total count of filtered result.
<div v-for="(item, businessIndex) in filterBy(items, filteredLocation)">
{{item}}
</div>
filterBy is method defined in methods block and filteredLocation is array of strings to filter out the selected locations if any.
filterBy: function (list, filteredLocation) {
return list.filter(function (item) {
var foundLocality = false
if (filteredLocation.length > 0) {
_each(filteredLocation, function (tempLocality) {
var localityRegExp = new RegExp(tempLocality, 'i')
if (localityRegExp.test(item.location)) {
foundLocality = true
}
})
if (!foundLocality) {
return
}
}
return item
})
}
I tried chaining the count as suggested by @yyx990803. Also tried with having seperate filter altogether suggested by @julienr114.
Any idea?
@pushkardeshmukh1992 try
<p>{{ filterBy(items, filteredLocation).length }}</p>
in your template
@julienr114
Yep it worked! Thanks ^^
I would like to know if there is any way to keep filteredLength binded? Instead of calculating the filter function each time,because calling filter function just to get length seems expensive.
@pushkardeshmukh1992 I think use computed properties is the better way in Vue to do this.