<template>
  <div class="online-view">
    <slot v-if="online"></slot>
    <slot v-else name="offline"></slot>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component
export default class OnlineView extends Vue {
  public online: boolean = navigator.onLine

  public mounted(): void {
    window.addEventListener('online', this.onchange)
    window.addEventListener('offline', this.onchange)
    this.$emit(this.online ? 'online' : 'offline')
  }

  public beforeDestroy(): void {
    window.removeEventListener('online', this.onchange)
    window.removeEventListener('offline', this.onchange)
  }

  public onchange(): void {
    this.online = navigator.onLine
    this.$emit(this.online ? 'online' : 'offline')
  }
}
</script>
