HappyJayXin
1/6/2019 - 3:22 PM

count.js

let vm = new Vue({
  el: '#app',
  data: {
    time: {
      content: '開始倒數',
      totalTime: null,
      canClick: true
    },
    notifyConfig: {
      title: '時間到',
      detail: {
        body: '點擊回畫面',
        icon: ''
      }
    }
  },
  methods: {
    handlecountDown() {
      if (!this.time.canClick) return
      this.time.canClick = false
      this.time.content = `倒數${this.time.totalTime}秒`
      let clock = setInterval(() => {
        this.time.totalTime--
        this.time.content = `倒數${this.time.totalTime}秒`
        if (this.time.totalTime < 0) {
          window.clearInterval(clock)
          this.time = {
            content: '開始倒數',
            totalTime: null,
            canClick: true
          }
          this.popNotice()
        }
      }, 1000)
    },
    popNotice() {
      if (window.Notification) {
        if (Notification.permission == 'granted') {
          const { title, detail } = this.notifyConfig
          const notification = new Notification(title, detail)
          notification.addEventListener('click', () => {
            window.focus()
          })
        }
      } else {
        alert('瀏覽器不支援!')
      }
    }
  }
})
<div id="app">
      <input
        type="text"
        placeholder="輸入倒數時間(秒)"
        v-model="time.totalTime"
        v-if="time.canClick"
      />
      <button @click="handlecountDown" :disabled="!time.canClick">
        {{ time.content }}
      </button>
</div>