为什么元素在 v-show 属性更改后没有隐藏?


<!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秒钟内不隐藏,然后再次显示?如何更改代码以实现此功能?

setTimeout不能这样工作。

它不会就此停止,等待并在5秒钟后继续。它立即继续到下一步,所以您立即将show更改为true。

setTimeout异步调用它的回调,这意味着它将在5秒钟后调用您赋予它的函数。

所以你需要这样做:

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

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

尝试在setTimeout内部运行切换

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

最新更新