延迟更改样式

时间:2018-10-10 14:58:51

标签: javascript html css vue.js vuejs2

我想在单击按钮后稍稍延迟一下div的样式。

如果我只是使用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>

3 个答案:

答案 0 :(得分:3)

我认为您遇到的问题是超时中的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>

EDIT 推荐的学习资源

this在JS中会变得非常棘手。如果您想了解更多,我强烈推荐Getify You Don't Know JS

推荐的相关This & Object Prototypes

答案 1 :(得分:0)

您可以使用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>

答案 2 :(得分:0)

您可以使用lodash的反跳方法。 https://lodash.com/docs/#debounce

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

在需要导入lodash之前

相关问题