gpt4 book ai didi

javascript - 将 setTimeout 函数分配给 Vue 方法

转载 作者:行者123 更新时间:2023-12-01 00:00:31 24 4
gpt4 key购买 nike

我当前已将 setTimeout 函数分配给 Vue 方法,并且我想为此函数使用clearTimeout。那可能吗?如果是这样,我该怎么做?

    methods: {
timeoutController() {
setTimeout(function() {
this.controllerShown = false;
}, 3000);
}
....

最佳答案

new Vue({
el: '#app',

data: {
timer: null
},

methods: {
startTimer () {
this.timer = setTimeout(() => {
console.log("execute me")
}, 3000)
},
// If you kill the timer before setTimeout callback has been executed the callback wont get executed
killTimer () {
if (this.timer) {
clearTimeout(this.timer)
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<button @click="startTimer()">start</button>
<button @click="killTimer()">kill</button>
</div>

关于javascript - 将 setTimeout 函数分配给 Vue 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60770304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com