【发布时间】:2021-07-22 19:43:25
【问题描述】:
我正在使用 Nuxtjs 构建一个应用程序。我想在应用程序中显示实时时钟。在我刷新页面之前,它会显示实时时钟。一旦我刷新页面,应用程序就会消失,并且会出现一条消息“ReferenceError: document is not defined”。 我将 Clock 组件放在 index.vue 文件中的标签内,但仍然遇到同样的问题。
index.vue 文件
<template>
<div>
<Navbar />
<Clock />
<Footer />
</div>
</template>
<script>
import Navbar from '../components/Navbar.vue'
import Footer from '../components/Footer.vue'
import Clock from '../components/Clock.vue'
export default {
components: {
Navbar,
Footer,
Clock,
},
}
</script>
<style scoped>
//ignore the css
</style>
Clock.vue
<template>
<div class="clock">
<span>{{ currentDate }}</span>
<span id="clock">{{ startTime() }}</span>
</div>
</template>
<script>
export default {
name: 'Clock',
data() {
return {
currentDate: new Date().toDateString(),
}
},
methods: {
startTime() {
const today = new Date()
let h = today.getHours()
let m = today.getMinutes()
let s = today.getSeconds()
let session = 'AM'
if (h === 0) {
h = 12
}
if (h > 12) {
h = h - 12
session = 'PM'
}
m = this.checkTime(m)
s = this.checkTime(s)
document.getElementById('clock').innerHTML =
h + ':' + m + ':' + s + session
setTimeout(this.startTime, 1000)
},
checkTime(i) {
if (i < 10) {
i = '0' + i
}
return i
},
},
}
</script>
<style scoped>
// ignore the css
</style>
【问题讨论】: