如何在Vue2中实现反跳功能?

vue.js Vue.js

达蒙

2020-03-09

我在Vue模板中有一个简单的输入框,我想像这样使用debounce或多或少:

<input type="text" v-model="filterKey" debounce="500">

但是,该debounce属性已在Vue 2中弃用该建议仅说:“使用v-on:input +第三方防抖功能”。

您如何正确实施?

我尝试使用lodashv-on:inputv-model来实现它,但是我想知道是否可以在没有额外变量的情况下进行操作。

在模板中:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

在脚本中:

data: function () {
  return {
    searchInput: '',
    filterKey: ''
  }
},

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

然后,在computed道具中使用filterkey

第373篇《如何在Vue2中实现反跳功能?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
小卤蛋小小 2020.03.09

如果您使用的是Vue,也可以使用v.model.lazy代替,debounce但请记住,v.model.lazy由于Vue限制了自定义组件的使用因此并非总是可以使用

对于自定义组件,应:value@change.native

<b-input :value="data" @change.native="data = $event.target.value" ></b-input>

小胖MandyGil 2020.03.09

如果您需要使用lodash的debounce函数应用动态延迟

props: {
  delay: String
},

data: () => ({
  search: null
}),

created () {
     this.valueChanged = debounce(function (event) {
      // Here you have access to `this`
      this.makeAPIrequest(event.target.value)
    }.bind(this), this.delay)

},

methods: {
  makeAPIrequest (newVal) {
    // ...
  }
}

和模板:

<template>
  //...

   <input type="text" v-model="search" @input="valueChanged" />

  //...
</template>

注意:在上面的示例中,我举了一个搜索输入示例,该输入可以通过自定义延迟调用API,该延迟在props

泡芙卡卡西神乐 2020.03.09

非常简单,没有lodash

  handleScroll: function() {
   if (this.timeout) clearTimeout(this.timeout); 
     this.timeout = setTimeout(() => {
       // your action
     }, 200);
  }
樱小胖 2020.03.09

我有同样的问题,这没有插件工作

因为<input v-model="xxxx">

<input
   v-bind:value="xxxx"
   v-on:input="xxxx = $event.target.value"
>

(资源)

我想我可以在xxxx的分配中设置一个反跳功能 xxxx = $event.target.value

像这样

<input
   v-bind:value="xxxx"
   v-on:input="debounceSearch($event.target.value)"
>

方法:

debounceSearch(val){
  if(search_timeout) clearTimeout(search_timeout);
  var that=this;
  search_timeout = setTimeout(function() {
    that.xxxx = val; 
  }, 400);
},
逆天泡芙神无 2020.03.09

请注意,我在接受答案之前发布了此答案。不对 这只是问题解决方案的一步。我已经编辑了接受的问题,以显示作者的实现以及我使用的最终实现。


基于注释和链接的迁移文档,我对代码进行了一些更改:

在模板中:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

在脚本中:

watch: {
  searchInput: function () {
    this.debounceInput();
  }
},

设置过滤键的方法保持不变:

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

看起来好像少了一个电话(只是v-model,而不是v-on:input)。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android