【问题标题】:How to access Vue Instance from within an argument function?如何从参数函数中访问 Vue 实例?
【发布时间】:2020-07-14 14:18:57
【问题描述】:

所以基于this thread我实现了这个sn-p:

methods: {
    checkSearchString: _.debounce( string => {
         console.log("watcher firing for search!");
         console.log(this.searchInput);
        this.$emit("search", this.searchInput);
    }, 2000)
},
watch: {
    searchInput : "checkSearchString"
}

但正如 cmets 在接受的答案中指出的那样,“this”并不指向 vue 实例,所以我无法访问它。如何从函数内访问 vue 实例?或者我怎样才能更好地解决这个问题?

这里的主要目标是使用 _.debounce 和观察者在用户停止输入时触发搜索,并以简洁的方式实现。

编辑:感谢您在此处指出使用箭头函数作为上下文问题,另一个线程上的用户确实指出这是问题,但我不明白为什么

【问题讨论】:

标签: vue.js


【解决方案1】:

你使用了失去上下文的箭头函数。 用普通的匿名函数来做

watch: {
    searchInput : "checkSearchString"
}

methods: {
    checkSearchString: _.debounce( function(value) {
         console.log("watcher firing for search!");
         console.log(value);
        this.$emit("search", value);
    }, 2000)
},

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 2015-09-11
    • 2021-09-02
    • 2018-06-13
    • 1970-01-01
    • 2020-06-14
    • 2017-09-15
    相关资源
    最近更新 更多