[英]Changing styles with delay
我想在單擊按鈕后延遲一些時間來切換div的樣式。
如果我簡單地使用類似this.customEffect = 'blueborder';
的代碼,則代碼可以正常工作this.customEffect = 'blueborder';
沒有超時。
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>
我認為您遇到的問題是超時中的this
上下文是匿名函數的而不是父對象。 您可以使用箭頭功能或顯式綁定。
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>
編輯推薦的學習資源
this
在JS中會變得非常棘手。 如果您想了解更多,我強烈推薦Getify This&Object Prototypes相關的《 You't Know JS》一書
您可以使用boostrap來避免編寫已經具有boostrap功能的代碼。
或者,您可以使自己的CSS類:
例如:
.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范例:
<div class="animated fadeIn fast">
<h1 class="display-4">My app</h1>
<p class="lead">This is a great app!</p>
<div>
您可以使用lodash的方法去抖動。 https://lodash.com/docs/#debounce
methods: {
start: _.debounce(function() {
this.customEffect = (this.customEffect == 'redtext')?'blueborder':'redtext';
},1000)
}
在您需要導入lodash之前
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.