IT이야기

Lodash 디바운드가 있는 Vue JS 시계를 올바르게 사용하는 방법

cyworld 2022. 3. 6. 10:57
반응형

Lodash 디바운드가 있는 Vue JS 시계를 올바르게 사용하는 방법

나는 lodash를 사용하여 다음과 같은 구성 요소에 대한 디바운스 함수를 호출하고 있다.

...
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
        }
    }
}
  • 이슈 1은 내 방법이checkSearchStr에 대해 모르다foo
  • 2번 문제는 내 가게가undefined뿐만 아니라.

왜 내 방법은 모를까?this통화가 되면._.debounce올바른 용법은 무엇인가?

네 시계는 이렇게 생겼어야 해.

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

그러나 이것은 좀 이례적이다.나는 네가 왜 시계를 버리고 싶은지 모르겠다.아마도 너는 그냥 그 일을 그만두는게 좋을거야.checkSearchStr방법의

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

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

한 가지 더 지적하고 싶은 것이 있는데, 암호의 어디에도 없다.searchStr규정된Vue로 값을 볼 때 데이터나 계산된 속성을 보고 있는 것이다.현재 정의한 바와 같이, watch on은searchStr절대 실행되지 않을 것이다.

@Bert가 논평에서 언급한 바와 같이this범위가 에 로컬이다.function그러므로, 만드는 것은this속성에 대한 범위data, 다음으로 변경:

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

외부 범위에 정의된 메소드를 호출해야 하기 때문에 디버깅된 함수는 화살표 함수의 완벽한 후보처럼 보인다.

watch: {
  searchStr: 'checkSearchStr'
},
methods: {
  checkSearchStr: _.debounce(val => {
    // `this` is the component instance (a.k.a. outer `this`)
    console.log(this)

    this.$store.dispatch('someMethod', val); 
  }, 100)
}

사용할 수 있는 상태에서 디바운드를 사용하는 올바른 방법this함수 내부:

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

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

참조URL: https://stackoverflow.com/questions/45178621/how-to-correctly-use-vue-js-watch-with-lodash-debounce

반응형