子組件
<template> <a class="getvalidate":class="{gray: (!stop)}"@click='clickHandler'> {{ stop ? '獲取驗證碼' : `(${mytimer})秒后重新獲取` }} </a> </template> <script> export default { name: 'getvalidate', data () { return { stop : true, mytimer: this.timer, Interval: null, } }, methods: { clickHandler (e) { if (this.stop) { // 調用外部綁定的倒計時,並且給它開關 this.$emit('click', this.startTimer); } }, update () { if (this.mytimer <= 1) { // 重置計數 this.mytimer = this.timer // 清除計時器 clearInterval(this.Interval) // 允許啟動倒計時 this.stop = true } else { // 倒計時 this.mytimer--; } }, startTimer () { // 開始循環執行update函數 this.Interval = setInterval(this.update, 1000) // 禁止啟動倒計時 this.stop = false; } }, props: { timer: { default: 60, type: Number } } }; </script> <style lang="scss" scoped> @import "./../sass/variables"; @import "./../sass/func"; .getvalidate { color: #0e6ae7; font-size: pxToRem(28px); width: 100%; text-align: right; &.gray { color: #999; } } </style>
父組件調用示例
<template> <div id="ForgetPwd"> <div class="form"> <mt-field topLabel = '請輸入手機號' errTopLabel='' type = "number" placeholder = '請輸入11位手機號碼' v-model = 'user' :maxlength = '11'></mt-field> <mt-field topLabel = '驗證碼' errTopLabel='' type = "number" placeholder = '請輸入6位驗證碼' v-model = 'validate' :maxlength = '6'> <getvalidate slot="icon" @click="getCode"></getvalidate> </mt-field> <button class="button" :class="{disable: user === '' || validate === ''}" @click="go">下一步</button> </div> </div> </template> <script> import mtField from '@components/field/field.vue' import Toast from '@components/toast/index.js' import Loader from '@components/loader/index.js' import getvalidate from '@myComponents/getvalidate' export default { name: 'ForgetPwd', data () { return { user:'13713332652', validate: '123456' } }, methods: { go () { }, getCode (cb) { Loader.show("正在獲取驗證碼") window.setTimeout(_ => { Loader.hideAll() cb() }, 2000) }, }, components: { mtField, getvalidate } } </script>