1. 程式人生 > >vue離開頁面清除定時器

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>