VueJs keydown 事件堆叠

VueJs keydown event stacking up

我正在构建一个 <textarea> 字段,一旦用户在上面输入内容,该字段就会开始淡出 v-on:keydown,但如果他继续输入,淡入淡出会重置,并保持 opacity: 1

但是,行为与预期不同。用户键入的越多,淡入淡出的速度越快,忽略 setTimeout 定义,并随着时间的推移恢复正常(例如:如果 <textarea> 上有一个字母,淡入淡出相应地表现;如果有是两个字母它运行s 两次淡出功能,第一次是双倍速度,第二次是正常速度;三个字母,3 倍,3 倍快一次...)。

这是我目前拥有的:

<textarea placeholder="Start typying your text here..." v-model="text" v-on:keydown="startFade" ref="textArea" style="opacity: 1"> </textarea>

方法:

methods: {
  fader(element) {

    if (element.style.opacity == 0) {
      this.text = ''
      element.style.opacity = 1
      console.log(element.style.opacity)
    } else {
      element.style.opacity = element.style.opacity - 0.1
      setTimeout(() => {
        console.log(element.style.opacity)
        this.fader(element)
      }, 1000);
    }
  },
  startFade() {
    let element = this.$refs.textArea;
    element.style.opacity = 1;
    setTimeout(() => {
      this.fader(element)
    }, 1000);
  }
}

我怎样才能阻止这些事件堆积起来,只 运行 一次?

我尝试添加一个clearTimeout()来重置功能,但是没有用。

```

!javascript

clearInterval

``` 应该成功了。你能展示一下你是如何使用它的吗?

要有效地使用 clearTimeout,您必须将之前 setTimeout 返回的值传递给它。

你的做法太DOM-oriented了,反正。您应该调整出现在 v-bind:style 中的变量。推子应该是连续运行的区间,按键事件重置变量。

new Vue({
  el: '#app',
  data: {
    op: 1,
    started: false
  },
  methods: {
    startOrReset() {
      if (this.started) {
        this.op = 1;
      } else {
        setInterval(() => {
          this.op -= 0.1;
          if (this.op < 0) {
            this.op = 0;
          }
        }, 1000);
        this.started = true;
      }
    }
  }
});
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <textarea :style="{opacity: op}" @keydown="startOrReset">
    Type something here before I disappear!
  </textarea>
</div>