封装一个vue倒计时组件

96 阅读1分钟
// 子组件
<template>
    <div>
        <span>{{ remainingTime }}</span>
    </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';

export default {
    props: {
        duration: {
            type: Number,
            required: true
        }
    },
    setup(props) {
        const remainingTime = ref(props.duration);
        let intervalId = null;

        const startCountdown = () => {
            if (remainingTime.value > 0) {
                intervalId = setInterval(() => {
                    remainingTime.value--;
                    if (remainingTime.value <= 0) {
                        clearInterval(intervalId);
                    }
                }, 1000);
            }
        };

        onMounted(() => {
            startCountdown();
        });

        onUnmounted(() => {
            clearInterval(intervalId);
        });

        return {
            remainingTime
        };
    }
};
</script>

调用子组件时传值, 必须要用 v-if="show" 来触发onMounted

  • 不使用会出现以下情况

第一次正常显示,第二次直接显示为0

  • 根据业务需求(第二种方法)

也可以直接使用父组件,调用子组件方法 startCountdown
这样就可以不使用 onMounted(() => { startCountdown(); });