<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <script src="https://unpkg.com/vue"></script>
  </head>
  <body>
    <div id="app">
      <p v-show="show">test</p>
      <button v-on:click="change">btn</button>
    </div>
    <script>
      var app = new Vue({
        el: "#app",
        data: {
          show: true
        },
        methods: {
          change: function () {
            this.show = false;
            setTimeout("", 5000);
            this.show = true;
          }
        }
      });
    </script>
  </body>
</html>为什么元素在按下按钮后不隐藏5秒,然后再次显示?以及如何更改代码以实现此功能?
发布于 2021-04-12 16:17:33
这直接将show设置为true。
console.log(false);
setTimeout(() => console.log("done"), 5000);
console.log(true);
setTimeout接受超时后执行的函数,这是您需要更改变量的地方:
new Vue({
  el: "#app",
  data: { show: true },
  methods: {
    change: function () {
      this.show = false;
      setTimeout(() => this.show = true, 5000);
    }
  }
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p v-show="show">test</p>
  <button v-on:click="change">btn</button>
</div>
发布于 2021-04-12 16:17:01
setTimeout不是那样工作的。
它不会停在那里,5秒后再继续。它立即继续到下一步,因此您立即将show更改为true。
setTimeout异步调用它的回调,这意味着它将在5秒后调用给它的函数。
所以你需要这样做:
setTimeout(() => this.show = true, 5000);
发布于 2021-04-12 16:16:28
尝试在setTimeout内部运行切换键
setTimeout(() => {
  this.show = true;
}, 5000);https://stackoverflow.com/questions/67061903
复制相似问题