In my Vue project, I have an array defined in the data() method that is populated through a custom directive in its bind hook. Here's the code snippet:
import Vue from 'vue'
export default {
el: '#showingFilters',
name: "Filters",
data() {
return {
country: '' // connected to a <select> element
states: [],
}
},
directives: {
arraysetter: {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = Object.keys(el.options).map(op => el.options[op].value);
},
},
},
methods: {
countryChangeHandler() {
this.states.splice(0)
fetch(`/scripts/statejson.php?country=${this.country}`)
.then(response => response.json())
.then(res => {
res.states.forEach( (element,i) => {
Vue.set(this.states, i, element.urlid)
});
})
},
}
The issue arises when I try to re-populate the states
array within the countryChangeHandler()
method, triggered by the @change
event on the country select tag.
Even though I clear the array using splice(0)
and use Vue.set
for reactive re-population, Vue does not recognize the changes! However, the array contains the correct elements. I am unsure how to make it reactive.
PS: I have tried finding a solution without using forEach
, but $set
requires an index to work properly.
I would greatly appreciate any assistance with this.