【问题标题】:“ReferenceError: document is not defined” in Nuxt.jsNuxt.js 中的“ReferenceError:文档未定义”
【发布时间】: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>

【问题讨论】:

    标签: vue.js nuxtjs


    【解决方案1】:

    在clock.vue中为你的元素添加ref,并在使用ref的方法中访问它。

    你的元素将是

    <span ref="clock">{{ startTime() }}</span>
    

    在你的方法中你可以引用它

    this.$refs.clock.innerHTML =  h + ':' + m + ':' + s + session
    

    【讨论】:

    • 它显示“无法设置未定义的属性'innerHTML'”
    • @rKuwar 在您的方法中,返回该值而不是设置 innerHTML
    猜你喜欢
    • 2019-02-20
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2016-09-04
    • 1970-01-01
    相关资源
    最近更新 更多