I have a Vue 2 application that uses an array of objects to back a search/multiselect widget provided by vue-multiselect.
I have looked at the Vue 1 -> 2 migration guide on debouncing calls, but the example they give did not propagate the arguments from the DOM elements to the business logic.
Right now the select fires change events with every keystroke, but I would like to throttle this (EG with lodash#throttle) so I'm not hitting my API every few milliseconds while they're typing.
import {mapGetters} from 'vuex';
import { throttle } from 'lodash';
import Multiselect from 'vue-multiselect'
export default {
components: {
Multiselect
},
data() {
return {
selectedWork: {},
works: [],
isLoading: false
}
},
computed: {
...mapGetters(['worksList']),
},
methods: {
getWorksAsync: throttle((term) => {
// the plan is to replace this with an API call
this.works = this.worksList.filter(work => titleMatches(work, term));
}, 200)
}
}
Problem: when the user types in the select box, I get the error:
TypeError: Cannot read property 'filter' of undefined
which is happening because this.worksList
is undefined
inside the throttle
function.
Curiously, when I use the dev tools debugger, this.worksList
has the value I need to dereference, with this
referring to the Vue component.
Currently I am not calling the API from within the component, but the problem remains the same:
- How can I throttle this call, and have the proper
this
context to update mythis.works
list? EDIT: this is explained in Vue Watch doesnt Get triggered when using axios - I also need to capture the user's query string from the multiselect widget to pass to the API call.
What is the proper pattern in Vue 2?