main.ts注册全局指令:
//main.ts
import * as directives from '@/directives/directives';
// 注册全局指令
Object.keys(directives).forEach(key => {
Vue.directive(key, (directives as { [key: string]: DirectiveOptions })[key])
})
//directives.ts
export * from './sms-timing/sms-timing';
// 2019-07-15 01:00 3094865027@qq.com
import { DirectiveOptions } from 'vue'
import { DirectiveBinding } from 'vue/types/options'
/**
使用示例:
<button v-sms-timing="sendSms">发送验证码</button>
sendSms(sms){
//倒计时
sms && sms();
}
*/
/**
* 倒计时秒数
*/
const COUNT_DOWN_SEC = 90;
/**
* 倒计时实现
* @param el
* @param binding
*/
const bindSmsTiming = (el: HTMLElement, binding: DirectiveBinding) => {
let countDownSec = COUNT_DOWN_SEC;
let interval = -1;
let oldBtnText = el.innerText;
let oldBackColor = el.style.backgroundColor;
el.onclick = () => {
if (interval != -1) {
return;
}
let countDown = () => {
//开始倒计时
el.style.backgroundColor = "gray";
el.innerHTML = countDownSec + " s";
interval = setInterval(() => {
countDownSec--;
if (countDownSec > 0) {
//变换按钮文字
el.innerHTML = countDownSec + " s";
} else {
//结束倒计时
el.innerHTML = oldBtnText;
el.style.backgroundColor = oldBackColor;
clearInterval(interval);
interval = -1;
countDownSec = COUNT_DOWN_SEC;
}
}, 1000);
}
//调用外部方法
binding.value(() => {
countDown();
});
}
}
/**
* 短信倒计时指令
*/
export const SmsTiming: DirectiveOptions = {
bind(el, binding) {
bindSmsTiming(el, binding)
},
update(el, binding) {
},
unbind(el, binding) {
}
}