在组件 method() 中访问 Vuex $store.getters

Q-s*_*sup 5 javascript vuex vuejs2

我正在尝试使用 Vuex 和 Vuetify 为搜索框异步填充下拉列表(https://vuetifyjs.com/components/selects)。我的问题是我无法使用方法()访问 $store,当然只能使用计算()。

这是我的吸气剂/状态:

loadedTours:Array[9]
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
8:Object
9:Object
Run Code Online (Sandbox Code Playgroud)

可以从计算()中使用 v-for 返回

tours () {
    return this.$store.getters.loadedTours
},
Run Code Online (Sandbox Code Playgroud)

这是一个仅当列表在 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

结果应返回每个对象中列出的旅游标题。

当前解决方案:

添加了创建():

created () {
    this.loadedTours = this.$store.getters.loadedTours
},
Run Code Online (Sandbox Code Playgroud)

将方法()更改为:

querySelections (v) {
    let that = this; 
    setTimeout(() => {
        that.items = that.loadedTours
    }, 500)
}
Run Code Online (Sandbox Code Playgroud)

删除了 data 属性处的箭头函数。

现在需要返回 tourTitle,然后按输入过滤。

sam*_*ayo 2

除了我在评论中提到的之外,您的主要错误可能是因为您this在箭头函数内部使用,因为this不会引用正确的(vuejs)上下文,

文档中:

请注意,您不应将箭头函数与 data 属性一起使用(例如 data: () => { return { a: this.myProp }})。原因是箭头函数绑定了父上下文,因此 this 不会是您期望的 Vue 实例,并且 this.myProp 将是未定义的。

而是做这样的事情:

  let that = this; 
  setTimeout(() => callback(that.name), 15); 
Run Code Online (Sandbox Code Playgroud)

现在,that将参考使用vuejsthis对象