vue離開頁面清除定時器

<script>
    export default {
        name:'test',
        data(){
            return {
                time: 60,
                timer:null,
            }
        }, 

        methods: {
            // 60s倒計時
            getLastTime: function(){
                this.timer = setInterval(function () {
                    if(this.time == 0){
                        this.time = 60;
                        clearInterval(this.timer);
                    }else {
                        this.time = this.time - 1;
                    }
                },1000) 
            },
        },
        destroyed(){
            if(this.timer) { //如果定時器在運行則關閉
                clearInterval(this.timer); 
            }
        }
    }
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章