说明:部分组件使用的是element-ui
子组件
<template> <div class="count-down"> <el-button type="primary" size="small" style="width:80px;" :disabled="disabled || time > 0"> {{ text }} </el-button> </div> </template> <script type="text/javascript"> export default { data() { return { time: 0 }; }, props: { second: { type: Number, default: 5 }, disabled: { type: Boolean, default: false } }, methods: { run: function() { this.time = this.second; this.timer(); }, timer: function() { if (this.time > 0) { this.time--; setTimeout(this.timer, 1000); } } }, computed: { text: function() { return this.time > 0 ? this.time + "s" : "获取验证码"; } } }; </script>
父组件
<template> <div> <count-down :disabled="disabled" @click="send" ref="btn"></count-down> </div> </template> export default { data () { return { disabled: false } }, methods: { send: function () { this.disabled = true; setTimeout(this.sended, 1000); }, sended() { this.$refs.btn.run(); this.disabled = false; } } }
这样写的时候,父组件的click事件是不生效的,在给某个组件监听一个原生事件的时候可以使用v-on的修饰符.native
<count-down :disabled="disabled" @click.native="GetVerifyCode" ref="countDownBtn"></count-down>
这样点击事件就生效了