简体   繁体   中英

Changing styles with delay

I want to switch the styles of the div with some delay after the button click.

The code will work fine if I simply will use something like this.customEffect = 'blueborder'; without timeouts.

 new Vue({ el: '#app', data: { customEffect: '' }, methods: { start: function() { setTimeout(function() { this.customEffect = 'blueborder'; }, 1000); setTimeout(function() { this.customEffect = 'redtext'; }, 2000); } } }); 
 .blueborder { border: 3px solid blue; } .redtext { color: red; } 
 <script src="https://npmcdn.com/vue/dist/vue.js"></script> <div id="app"> <div> <button @click="start">Start</button> <div :class="customEffect">Some text</div> </div> </div> 

I think the problem you are having is the this context in your timeouts is the anonymous function's, not the parent object. You can use either arrow functions or an explicit binding.

 new Vue({ el: '#app', data: { customEffect: '' }, methods: { start: function() { setTimeout((function() { //BIND this.customEffect = 'blueborder'; }).bind(this), 1000); setTimeout(() => { //OR => this.customEffect = 'redtext'; }, 2000); } } }); 
 .blueborder { border: 3px solid blue; } .redtext { color: red; } 
 <script src="https://npmcdn.com/vue/dist/vue.js"></script> <div id="app"> <div> <button @click="start">Start</button> <div :class="customEffect">Some text</div> </div> </div> 

EDIT Recommended learning resources

this can get pretty tricky in JS. If you want to learn more about it I highly recommend the relevant You Don't Know JS book by Getify This & Object Prototypes

You can use boostrap to avoid making code that already have the boostrap features.

Or you can make you own css classes:

For example:

.animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}

.fast {
-webkit-animation-duration: 0.4s;
animation-duration: 0.4s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}

@keyframes fadeIn {
from {
  opacity: 0;
}

to {
  opacity: 1;
}
}

.fadeIn {
animation-name: fadeIn;

html example:

<div class="animated fadeIn fast">
  <h1 class="display-4">My app</h1>
  <p class="lead">This is a great app!</p>
<div>

You can use the method debounce of lodash. https://lodash.com/docs/#debounce

 methods: {
        start: _.debounce(function() {
            this.customEffect = (this.customEffect == 'redtext')?'blueborder':'redtext';
        },1000)
      }

before you need to import lodash

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