Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

vue搜索节流为什么第一种方法不可以呢,第二种就可以

第一种
watch: {

quickSearch(val) {
  let timer = null
  if (timer !== null) clearTimeout(timer)
  timer = setTimeout(() => {
    this.loading = true
    this.init()
  }, 2000)
  // this.$emit('sonParameters', val)
 }
}

第二种
const delay = (function () {
let timer = 0
  return function (callback, ms) {
    clearTimeout(timer)
    timer = setTimeout(callback, ms)
  }
})()

quickSearch(val) {
  delay(() => {
    this.loading = true
    this.init()
  }, 1000)
},
我不太懂其中原理,哪位前辈能给说说

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

1 Answer

0 votes
by (71.8m points)

你第一种代码有问题 - -这个节流代码做跟不做一样。只是延迟触发时间2秒,timer都是watch重新声明的,根本没有清除到上一次所产生到timeout。2秒连续改变10次状态,只不过是2秒后连续触发十次
vue简单示例

data: {
    timer: null,
    inputText: ''
},
watch: {
    inputText(val) {
        if (this.timer) clearTimeout(this.timer)
        this.timer = setTimeout(() => this.init(), 2000)
    }
},

原因:
第一种每次执行watch时候重新声明了timer。
第二种生效是因为你使用了闭包,内部函数访问timer变量在当前作用域下找不到就提升到外部作用域寻找timer,然后就形成了引用外部timer变量到关系,外部timer就不会被标记清除。所以你每次调用返回的内部函数都是访问第一次闭包产生的timer,所以第二种生效可用


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...