如何仅触发一次vue方法,而不是每次都触发一次 [英] How to trigger a vue method only once, not every time

查看:3097
本文介绍了如何仅触发一次vue方法,而不是每次都触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即使在更改处理旋转:

<div @change="handleRotate"></div>
<script>
export default {
  data: {
    rotate = 0
  },
  methods: {
    handleRotate () {
      this.rotate = this.rotate + this.getRotateAngle(e.clientX, e.clientY)
    }
  }
}
</script>

现在,第二个 this.rotate 在每个更改上运行。我该怎么做才能在第一次 handleRotate 运行时第二次应用第二个 this.rotate

Right now, the second this.rotate runs on every change. How can I do it so that the second this.rotate is applied only the first time handleRotate runs?

推荐答案

解决方案Vue方式:



您可以使用 $ once ,它只会监听一次事件。

Solving it Vue way:

You can use $once, which will listen for a event but only once.


收听自定义事件,但只收听一次。第一次触发时,侦听器将被删除。

Listen for a custom event, but only once. The listener will be removed once it triggers for the first time.

您只需要添加 .once @change 如下:

<div @change.once="handleRotate"></div>
<script>
export default {
  //No Change here
}
</script>

检查演示是否在小提琴

旧答案:

如果你不想为 rotate 设置初始值,你可以再增加一个变量: hasRotated 来跟踪旋转是否已更改。最初将 hasRotated 设置为true,一旦旋转已更改,将 hasRotated 设置为false,如下所示:

If you do not want to have initial value set for rotate, you can have one more variable : hasRotated to track whether rotate has been changed or not. Initially set hasRotated to true, once rotate has been changed set hasRotated to false, like following:

<div @change="handleRotate"></div>
<script>
export default {
  data: {
    rotate: 123,
    hasRotated: false
  },
  methods: {
    handleRotate () {
      if(this.hasRotated){
        this.rotate = this.rotate + this.getRotateAngle(e.clientX, e.clientY)
        this.hasRotated = false
      }
    }
  }
}
</script>

这篇关于如何仅触发一次vue方法,而不是每次都触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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