只需使用Vue的反应性
用
ref()
定义你的变量
const days = ref(0);
并使用
.value
在您的函数中设置它们:
days.value = Math.floor(timeleft / (1000 * 60 * 60 * 24));
const { createApp, ref } = Vue;
const countDownDate = new Date("Apr 28, 2023 16:37:52").getTime();
const App = {
setup() {
const days = ref(0);
const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);
const myfunc = setInterval(function() {
const now = new Date().getTime();
var timeleft = countDownDate - now;
days.value = Math.floor(timeleft / (1000 * 60 * 60 * 24));
hours.value = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
minutes.value = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
seconds.value = Math.floor((timeleft % (1000 * 60)) / 1000);
}, 1000)
return { days, hours, minutes, seconds }
}
}
const app = createApp(App);
app.mount('#app');
#app { line-height: 1.5; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
<b>Countdown:</b><br/>
<p> Days {{ days }}, Hours {{ hours }}, Minutes: {{ minutes }}, Seconds: {{ seconds }} </p>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
配合手表效果工作。
<template>
<div>
<p>Countdown: {{ `${days}` }} {{ hours }} {{ minutes }} {{ seconds }} </p>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue';
export default {
setup() {
const countDownDate = new Date('Apr 28, 2023 16:37:52').getTime();
const days = ref(0);
const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);
watchEffect(() => {
const now = new Date().getTime();
const timeleft = countDownDate - now;
days.value = Math.floor(timeleft / (1000 * 60 * 60 * 24));
hours.value = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 *
60));
minutes.value = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
seconds.value = Math.floor((timeleft % (1000 * 60)) / 1000);
});
return { days, hours, minutes, seconds };
},
};
</script>