如何在Lodash防抖中正确使用Vue JS手表 [英] How to correctly use Vue JS watch with lodash debounce

查看:309
本文介绍了如何在Lodash防抖中正确使用Vue JS手表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用lodash在这样的组件上调用去抖功能:

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
        }
    }
}

  • 问题1是我的方法checkSearchStr不了解foo
  • 问题2是我的商店也是undefined
    • Issue 1 is that my method checkSearchStr doesn't know about foo
    • Issue 2 is that my store is undefined as well
    • 为什么通过_.debounce调用时我的方法不知道this?正确的用法是什么?

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

      推荐答案

      您的手表应该看起来像这样.

      Your watch should look like this.

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

      但是,这有点不寻常.我不明白您为什么要对手表进行防抖.可能您只想对checkSearchStr方法进行反跳操作即可.

      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)
      }
      

      我想指出的另一件事是:在代码中的searchStr中没有定义的地方.当您使用Vue观看值时,您正在观看数据或计算属性.按照您当前的定义,searchStr上的监视将永远不会执行.

      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.

      这篇关于如何在Lodash防抖中正确使用Vue JS手表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆