Reputation: 1793
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>
Upvotes: 1
Views: 2469
Reputation: 1
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
Upvotes: 0
Reputation: 1967
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>
Upvotes: 0
Reputation: 2658
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
Upvotes: 5