“ReferenceError: document is not defined” in Nuxt.js

Viewed 994

I am building an app using Nuxtjs. I want to show the live clock in the app. It is showing a live clock until I refresh the page. Once I refresh the page the app gets vanished and a message come “ReferenceError: document is not defined”. I placed the Clock component inside tags in index.vue file but still getting the same issue.

index.vue file

<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>

1 Answers

Add ref to your element in the clock.vue and access it in the method using ref.

Your element will be

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

In your methode you can reference it with

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