【问题标题】:Why element isn't hidden after changes of v-show attribute?为什么 v-show 属性更改后元素不隐藏?
【发布时间】:2021-07-07 17:48:33
【问题描述】:
<!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 秒不隐藏然后又显示? 以及如何修改代码来实现这个功能?

【问题讨论】:

    标签: javascript html vue.js web


    【解决方案1】:

    setTimeout 不能这样工作。

    它不会停在那里,等待并在 5 秒后继续。它立即继续到下一步,因此您立即将 show 更改为 true。

    setTimeout 异步调用它的回调,这意味着它会在 5 秒后调用你给它的函数。

    所以你需要这样做:

    setTimeout(() =&gt; this.show = true, 5000);

    【讨论】:

      【解决方案2】:

      这直接将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>

      【讨论】:

        【解决方案3】:

        尝试在setTimeout 中运行切换

        setTimeout(() => {
          this.show = true;
        }, 5000);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-04-27
          • 1970-01-01
          • 2018-10-07
          • 1970-01-01
          • 2019-07-13
          • 2021-10-29
          • 1970-01-01
          相关资源
          最近更新 更多