Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

javascript - How to correctly use Vue JS watch with lodash debounce

I'm using lodash to call a debounce function on a component like so:

...
import _ from 'lodash';

export default {
    store,
    data: () => {
        return {
            foo: "",
        }
    },

    watch: {
        searchStr: _.debounce(this.default.methods.checkSearchStr(str), 100)
    },

    methods: {
        checkSearchStr(string) {
            console.log(this.foo) // <-- ISSUE 1
            console.log(this.$store.dispatch('someMethod',string) // <-- ISSUE 2
        }
    }
}
  • Issue 1 is that my method checkSearchStr doesn't know about foo
  • Issue 2 is that my store is undefined as well

Why doesn't my method know this when called through _.debounce? And what is the correct usage?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your watch should look like this.

watch: {
    searchStr: _.debounce(function(newVal){
      this.checkSearchStr(newVal)
    }, 100)
},

This is a bit unusual, however. I don't see why you would want to debounce a watch. Possibly you would rather just debounce the checkSearchStr method.

watch: {
    searchStr(newVal){
      this.checkSearchStr(newVal)
    }
},

methods: {
    checkSearchStr: _.debounce(function(string) {
        console.log(this.foo) 
        console.log(this.$store.dispatch('someMethod',string)) 
    }, 100)
}

One other thing I would like to point out; no where in the code is searchStr defined. When you watch a value with Vue, you are watching a data or computed property. As you have currently defined it, the watch on searchStr will never execute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...