Yago Massiah
Yago Massiah

Reputation: 3

How to access Vue Instance from within an argument function?

So based off this thread I implemented this snippet:

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

but as comments on the accepted answer pointed out, "this" does not points to the vue instance, so I can't access it. How could I access the vue instance from within the function? or how could I solve this better?

the main goal here is to use _.debounce and a watcher to fire the search when the user stops typing, and achieve that in a clean way.

Edit: Thanks for pointing the use of the arrow function as the problem of context here, the users on the other thread did point to this being the problem but I didn't get why

Upvotes: 0

Views: 122

Answers (1)

user13198697
user13198697

Reputation:

you using arrow function which losing context. do it with normal anonymous function

watch: {
    searchInput : "checkSearchString"
}

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

Upvotes: 1

Related Questions