javascript - 延迟更改样式

标签 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>

最佳答案

我认为您遇到的问题是超时中的 this 上下文是匿名函数的,而不是父对象。您可以使用箭头函数或显式绑定(bind)。

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 中可能会变得非常棘手。如果你想了解更多,我强烈推荐相关的You Don't Know JS Getify 预订 This & Object Prototypes

关于javascript - 延迟更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52743154/

相关文章:

javascript - 动态添加/删除多个输入字段

javascript - Select2 占位符并不总是出现

javascript - AngularJS:模板中的第二个应用程序不起作用

CSS 边距 :auto unequal

CSS - 按钮有时无法点击?

javascript - 如何使用 P5js 将 DOM 元素拖入 Canvas 而不离开 Canvas ?

javascript - 索引超出范围异常 : Array index is out of range

javascript - Web 扩展 - document.getElementById 在执行异步方法之前返回 null

html - li 元素上方不需要的空格

html - 垂直居中多行 flex 元素