Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Vuex $store.getters in component method()

I am trying to populate a dropdown Asynchronously (https://vuetifyjs.com/components/selects) using Vuex and Vuetify for a search box. My problem is that I cannot access the $store using the method(), only computed() of course.

Here are my getters/state:

loadedTours:Array[9]
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
8:Object
9:Object

which can be returned using v-for from the computed()

tours () {
    return this.$store.getters.loadedTours
},

Here is a method() that works only if the list is in the data():

methods: {
    querySelections (v) {
        this.loading = true
            setTimeout(() => {
                this.items = this.tours.filter(e => {
                    return (e || '').toLowerCase().indexOf((v || '').toLowerCase()) > -1
                })
            this.loading = false
        }, 500)
    }
}

The result should return the tour titles listed in each object.

Current solution:

added created():

created () {
    this.loadedTours = this.$store.getters.loadedTours
},

changed method() to:

querySelections (v) {
    let that = this; 
    setTimeout(() => {
        that.items = that.loadedTours
    }, 500)
}

Removed the arrow function at the data property.

Now need to return the tourTitle, then filter by the input.

like image 705
Q-sup Avatar asked Oct 29 '22 22:10

Q-sup


1 Answers

In addition to what I mentioned in the comments, your main error is probably because you are using this inside the arrow function, because this will not refer to the right (vuejs) context,

From the documentation:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.

instead do something like this:

  let that = this; 
  setTimeout(() => callback(that.name), 15); 

Now, that will refer to use vuejs this object

like image 187
samayo Avatar answered Nov 11 '22 08:11

samayo