【发布时间】:2023-02-03 02:13:30
【问题描述】:
我有以下组件,它是一个非常简单的 0 倒计时。当倒计时达到 0 时,它会触发重定向。当我将这个组件放在我的页面上时,onMounted 函数会触发 interval(counterFunc())。当我将它隔离到一个组件中时,interval(counterFunc()) 不会触发。我怎样才能解决这个问题?
<template>
{{ counter }}
</template>
<script setup lang="ts">
const props = defineProps<{
time: number;
}>();
let counter = toRef(props, 'time')
const counterFunc = () => {
setInterval(() => {
counter.value--;
if (counter.value == 0) {
clearError({redirect: '/'})
}
}, 1000);
};
onMounted(() => {
counterFunc();
});
在模板中使用它:
<AppCountdown :time=10></AppCountdown>
【问题讨论】:
-
你不应该改变道具。
counter = toRef(props, 'time')与 props.time 同步计数器,因此即使您执行counter.value--也与尝试执行props.time--相同。如果你只是做let counter = ref(props.time),它应该可以工作。如果props.time在挂载时并不总是可用,您可能还想考虑添加一个观察者