简体   繁体   中英

javascript run function only once per button click

I use vue.js to handle some button clicks and run a method. So a button like

<button id="signup-photo-button" v-on:click="photo">{{ photoButton }}</button>

will run this method just fine:

photo: function(){

   if( vm.photoButton == 'Next, Declare Your Goal')
   {
        photoUpload();                 
    } else {
        sliderSignup.unslider('next');
    }

 }

the trouble is a double click can run sliderSignup.unslider('next'); twice skipping two slides, not good. I know there is the jquery function .one() you can use on a button click, but I use Vue. How can I run this function only once or like once every 10 secs so you cant double click real fast? I have look a lot and only see the option of a $('#element').one('click' function(){}) via jquery which wont work for me.

According to Vue Event-Modifiers you can use: .once

Change your code from:

<button id="signup-photo-button" v-on:click="photo">{{ photoButton }}</button>

to:

<button id="signup-photo-button" v-on:click.once="photo">{{ photoButton }}</button>

With Vue version 1 you may use a variable like in:

 new Vue({ el: '#example-2', data: { isAlreadyClicked: true, photoButton: 'button demo' }, methods: { photo: function (event) { if (this.isAlreadyClicked) { this.isAlreadyClicked = false; console.log('do your stuff'); } else { console.log('already clicked. Do nothing'); } } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script> <div id="example-2"> <button id="signup-photo-button" v-on:click="photo">{{ photoButton }}</button> </div>

Following @baao idea

 photo: function(){

       if( vm.photoButton == 'Next, Declare Your Goal')
       {
            photoUpload();                 
        } else {
            document.getElementById('signup-photo-button').disabled = true;
            setTimeout(function() {
                 document.getElementById('signup-photo-button').disabled = false; 
    }
,10000);
            sliderSignup.unslider('next');
        }
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM