...struggling to pass the filterCriteria into the filter function.
Is there any way to do it efficiently without having to create a new function?
A solution is available. Firstly, you can use an arrow function for the callback:
filtered () {
return this.items.filter(item => item.status === this.query)
}
Alternatively, you can retain a reference to the this
object:
filtered () {
var vm = this
return this.items.filter(function (item) {
item.status === vm.query
})
}
Here is a complete example:
var todoList = new Vue({
el: '#todolist',
data: {
query: 'Done',
items: [
{content: 'Fishing.', status: 'Done'},
{content: 'Do homework.', status: 'Ongoing'}
]
},
computed: {
filtered () {
return this.items.filter(item => item.status === this.query)
}
}
})
<div id="todolist">
<div>
<button @click="query='Ongoing'">Ongoing</button>
<button @click="query='Done'">Done</button>
</div>
<div v-for="item, idx in filtered" :key="idx">
<span>{{item.status}}:</span>
<span>{{item.content}}</span>
</div>
</div>
<script src="https://unpkg.com/vue"></script>