带有setInterval的reactive vue函数

5gfr0r5j  于 2023-08-07  发布在  Vue.js
关注(0)|答案(2)|浏览(130)

我想让这个功能更新evry 1000ms

const countDaysLeft = (date) => {
    let dateNow = new Date().getTime();
    let countDate = new Date(date).getTime();
    let dateDiff = countDate - dateNow;
    let days = Math.floor(dateDiff / 1000);
    return days;
};

字符串
我试过这样做

const countDaysLeft = (date) => {
  return setInterval(() => {
    let dateNow = new Date().getTime();
    let countDate = new Date(date).getTime();
    let dateDiff = countDate - dateNow;
    let days = Math.floor(dateDiff / 1000);
    return days;
  }, 1000);
};


在这里我试图在页面中显示它

<div
    class="w-full h-32 p-2 rounded-md text-gray-100 flex flex-col 
    justify-between"
    v-for="countdown in countdownsArray"
    :id="countdown.id"
  >
    <h1 class="text-2xl font-bold">{{ countdown.title }}</h1>
    <h1 class="text-lg font-semibold">
      {{ countDaysLeft(countdown.date) }}
    </h1>
    <h1 class="text-sm text-gray-200">{{ countdown.date }}</h1>
  </div>


但它仍然不工作,任何想法,使我的功能React?

8iwquhpp

8iwquhpp1#

使用Vue 3的React性系统。我喜欢用script setup写作。

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

const daysLeft = ref(0)

let intervalId

onMounted(() => {
  intervalId = setInterval(() => {
    const dateNow = Date.now()
    const countDate = new Date('2024-12-31').getTime()
    const dateDiff = countDate - dateNow
    daysLeft.value = Math.floor(dateDiff / (1000 * 60 * 60 * 24))
  }, 1000)
})

onUnmounted(() => clearInterval(intervalId))
</script>

<template>
  <div>
    Days Left: {{ daysLeft }}
  </div>
</template>

字符串
很直接,对吧?

v8wbuo2f

v8wbuo2f2#

实际的方法与this answer中建议的方法相同,但根据最近的详细信息,它是一个值数组,而不是需要计算的单个值。

let intervalId;
let daysArray = reactive([]);

onMounted(() => {
  daysArray.length = countdownsArray.length;

  intervalId = setInterval(() => {
    countdownsArray.forEach((date, i) => {
      daysArray[i] = countDaysLeft(i);
    });
  }, 1000)
});

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

...

<template>
    <div v-for="(countdown, i) in countdownsArray"
    :id="countdown.id"
  >
    ...
    {{ daysArray[i] }}
    ...

字符串
Vue 2中的数组的突变还需要使用Vue.set

相关问题