<!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>
Why does the element not hide for 5 seconds after pressing the button and then show again? And how can I change the code to achieve this function?
Advertisement
Answer
This directly sets show
to true
:
console.log(false); setTimeout(() => console.log("done"), 5000); console.log(true);
setTimeout
takes a function to be executed after the timeout, this is where you need to change the variable:
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>