How to call vue method only once, not every time

I handle the rotation even on change :

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

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

+5
source share
3 answers

Vue solution:

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

Listen to a custom event, but only once. The listener will be deleted after its launch for the first time.

You just need to add .once to @change , as shown below:

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

Check out the demo if it's in the fiddle .


Old answer:

If you don't want to have the initial value set for rotate , you can have another variable: hasRotated to keep track of whether the rotation has changed or not. The hasRotated value is hasRotated true, after the rotation has been changed, set hasRotated to false, as shown below:

 <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> 
+5
source

one simple solution would be to add a marker something 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 will need to trigger this.rotated as false

+4
source

If rotate always starts from scratch, 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); } } }; 
+1
source

Source: https://habr.com/ru/post/1261767/


All Articles