1. 程式人生 > 其它 >點選按鈕進行倒計時元件,使用父元件觸發子元件事件

點選按鈕進行倒計時元件,使用父元件觸發子元件事件

技術標籤:vue

在這裡插入圖片描述

場景:做題場景,規定時間90min,點選按鈕開始,如上圖
知識補給:父元件如何觸發子元件事件
本案例:點選父元件中的按鈕,觸發子元件的倒計時開始事件
父元件:this.$refs.child.$emit('childcountdown','這裡寫要傳給子元件的值')
start() { this.$refs.child.$emit('childcountdown') },
子元件:

 this.$on('childcountdown', (res) => {
 		console.log(res)  //  這裡是從父元件傳來的值(這裡寫要傳給子元件的值)
          this.countdown() // 調子元件中的倒計時開始事件
  })

父元件

<template>
  <div style="margin-top:20px">
    <Button @click="start">點選開始模擬測驗</Button>
    <count-down ref="child" :duration="duration"></count-down>
  </div>
</template>
<script>
import countDown from './components/countDown.vue'
export default {
  components: { countDown },
  data() {
    return {
      duration: 90*60*1000
    }
  },
  methods: {
    start() {
      this.$refs.child.$emit('childcountdown')
    },
  }
}
</script>
<style scoped>

</style>

countDown子元件

<template>
    <div style="margin-top:20px">
        <div class="time">{{hour}}:{{minites}}:{{second}} </div>
    </div>
</template>
<script>
import util from '@/libs/util'
export default {
  props:{
    duration:{
      type:Number,
      default:null
    }
  },
  data() {
    return {
       day:0,
       hour:'00',
       minites:'00',
       second:'00',
       times:0,
       startTime: 0
    }
  },
  created(){
     this.init()
  },
  methods: {
    init(){
      this.$on('childcountdown', (res) => {
          this.startTime = Date.parse(new Date())
          this.countdown()
      })
    },
    countdown () {
        const now = Date.parse(new Date())
        const end = this.startTime + this.duration
        let times = end - now
        if(times < 0) return false;
        this.day = parseInt(times / 1000 / 60 / 60 / 24)
        this.hour = parseInt(times / 1000 / 60 / 60 % 24)
        this.minites = parseInt(times / 1000 / 60 % 60)
        this.second = parseInt(times / 1000 % 60)
        // 個位數前補零
        this.hour = this.hour > 9 ? this.hour : '0' + this.hour
        this.minites = this.minites > 9 ? this.minites : '0' + this.minites
        this.second = this.second > 9 ? this.second : '0' + this.second
        setTimeout(()=> {
            this.countdown()
        }, 1000)
    }
    
  },
  mounted() {
  },
  watch: {
    
  },
  computed: {
    
  },
}
</script>
<style scoped>
.time{
    font-size: 30px;
    font-weight: 600;
}
</style>