【问题标题】:Component not firing after onMounted is called调用 onMounted 后组件未触发
【发布时间】: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 在挂载时并不总是可用,您可能还想考虑添加一个观察者

标签: vue.js vuejs3


【解决方案1】:

这是一个工作示例:

<script setup lang="ts">
import { defineProps, ref, onMounted, toRef } from "vue";

const props = defineProps<{
  time: number;
}>();

const counter = ref(props.time); // set a proper ref that can be mutated

const counterFunc = () => {
  setInterval(() => {
    counter.value = counter.value - 1; // mutate the ref as expected
    if (counter.value == 0) {
      console.log("clearError"); // replace with your clear error function
    }
  }, 1000);
};

onMounted(counterFunc);
</script>

<template>
  {{ counter }}
</template>

你可以在这里试试:https://codesandbox.io/s/heuristic-stallman-niiqzl?file=/src/App.vue:0-419

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2011-09-30
    • 1970-01-01
    • 2014-04-05
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2018-11-27
    相关资源
    最近更新 更多