How to trigger a vue method only once, not every time

后端 未结 3 1535
情深已故
情深已故 2021-01-11 10:28

I\'m handling a rotate even on change:

相关标签:
3条回答
  • 2021-01-11 10:35

    If rotate start always at zero you can do:

    export default {
        data: {
            rotate = 0
        },
        methods: {
            handleRotate(e) {
                if (this.rotate !== 0) {
                    return;
                }
                this.rotate = this.rotate + this.getRotateAngle(e.clientX, e.clientY);
            }
        }
    };
    
    0 讨论(0)
  • 2021-01-11 10:39

    one simple solution would be to add a marker somewhat like this:

    <script>
    export default {
      data: {
        rotate = 0
      },
      methods: {
        handleRotate () {
          if(!this.rotated){
              this.rotate = this.rotate + this.getRotateAngle(e.clientX, e.clientY);
              this.rotated = true;
          }
        }
      }
    }
    </script>
    

    of course you would need to initiate this.rotated as false

    0 讨论(0)
  • 2021-01-11 11:00

    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.

    You just need to add .once to @change like following:

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

    Check demo if this in the fiddle.


    Old Answer:

    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>
    
    0 讨论(0)
提交回复
热议问题