vk-data-verification-code.vue 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <template>
  2. <view class="vk-data-verification-code">
  3. <view @click="sendSmsCode" :style="customStyle">
  4. <slot :tips="tips" :sec-num="secNum">{{ tips }}</slot>
  5. </view>
  6. </view>
  7. </template>
  8. <script>
  9. const localeObj = {
  10. "zh-Hans":{
  11. "startText":"获取验证码",
  12. "changeText":"X秒重新获取",
  13. "endText":"重新获取",
  14. "tryAgainInSeconds":"秒后再重试",
  15. "pleaseEnterTheCorrectMobileNumber":"请输入正确的手机号码",
  16. "sending":"发送中...",
  17. "verificationCodeSent":"验证码已发送",
  18. "triggerDayLevelFlowControl":"触发天级流控",
  19. "pleaseTryAgainTomorrow":"短信发送频繁,请明日再试!",
  20. "pleaseTryAgainIn1Hour":"短信发送频繁,请过1小时后再试!",
  21. "triggerMinuteLevelFlowControl":"触发分钟级流控",
  22. "pleaseTryAgainLater":"短信发送频繁,请稍后再试!",
  23. },
  24. "zh-Hant":{
  25. "startText":"獲取驗證碼",
  26. "changeText":"X秒重新獲取",
  27. "endText":"重新獲取",
  28. "tryAgainInSeconds":"秒後再重試",
  29. "pleaseEnterTheCorrectMobileNumber":"請輸入正確的手機號碼",
  30. "sending":"發送中...",
  31. "verificationCodeSent":"驗證碼已發送",
  32. "triggerDayLevelFlowControl":"觸發天級流控",
  33. "pleaseTryAgainTomorrow":"短信發送頻繁,請明日再試!",
  34. "pleaseTryAgainIn1Hour":"短信發送頻繁,請過1小時後再試!",
  35. "triggerMinuteLevelFlowControl":"觸發分鐘級流控",
  36. "pleaseTryAgainLater":"短信發送頻繁,請稍後再試!",
  37. },
  38. "en":{
  39. "startText":"Get code",
  40. "changeText":"X second reacquire",
  41. "endText":"Reacquire",
  42. "tryAgainInSeconds":"Try again in seconds",
  43. "pleaseEnterTheCorrectMobileNumber":"Please enter the correct mobile number",
  44. "sending":"Sending...",
  45. "verificationCodeSent":"Verification code sent",
  46. "triggerDayLevelFlowControl":"Trigger day level flow control",
  47. "pleaseTryAgainTomorrow":"SMS sent frequently, please try again tomorrow!",
  48. "pleaseTryAgainIn1Hour":"SMS sent frequently, please try again in 1 hour",
  49. "triggerMinuteLevelFlowControl":"Trigger minute level flow control",
  50. "pleaseTryAgainLater":"SMS sent frequently, please try again later",
  51. }
  52. };
  53. /**
  54. * verificationCode 验证码输入框
  55. * @property {String} mode 模式,mobile 手机验证码 custom 自定义验证码 默认 mobile
  56. * @property {String} mobile 接收短信的手机号
  57. * @property {String} type 短信类型,如 register、login、bind、unbind
  58. * @property {Number String} seconds 倒计时所需的秒数(默认60)
  59. * @property {Object String} customStyle 自定义样式
  60. * @property {String} start-text 开始前的提示语,见官网说明(默认获取验证码)
  61. * @property {String} change-text 倒计时期间的提示语,必须带有字母"x",见官网说明(默认X秒重新获取)
  62. * @property {String} end-text 倒计结束的提示语,见官网说明(默认重新获取)
  63. * @property {Boolean} keep-running 是否在H5刷新或各端返回再进入时继续倒计时(默认false)
  64. * @event {Function} change 倒计时期间,每秒触发一次
  65. * @event {Function} start 开始倒计时触发
  66. * @event {Function} end 结束倒计时触发
  67. * @event {Function} send 自定义发送事件 当mode=custom时会有此事件
  68. * @example <vk-data-verification-code seconds="60" :mobile="form1.mobile" type="register" custom-style="font-size: 28rpx;"></vk-data-verification-code>
  69. */
  70. export default {
  71. name: 'vk-data-verification-code',
  72. emits: ['start', 'end', 'change','send','codeChange'],
  73. props: {
  74. // 模式,mobile 手机验证码 custom 自定义验证码 默认 mobile
  75. mode: {
  76. type: String,
  77. default: 'mobile'
  78. },
  79. // 接收短信的手机号
  80. mobile: {
  81. type: String
  82. },
  83. // 短信类型,如 register、login、bind、unbind
  84. type: {
  85. type: String,
  86. default: 'login'
  87. },
  88. customStyle: {
  89. type: [String,Object]
  90. },
  91. // 倒计时总秒数
  92. seconds: {
  93. type: [String, Number],
  94. default: 60
  95. },
  96. // 尚未开始时提示
  97. startText: {
  98. type: String,
  99. default: ''
  100. },
  101. // 正在倒计时中的提示
  102. changeText: {
  103. type: String,
  104. default: ''
  105. },
  106. // 倒计时结束时的提示
  107. endText: {
  108. type: String,
  109. default: ''
  110. },
  111. // 是否在H5刷新或各端返回再进入时继续倒计时
  112. keepRunning: {
  113. type: Boolean,
  114. default: false
  115. },
  116. // 为了区分多个页面,或者一个页面多个倒计时组件本地存储的继续倒计时变了
  117. uniqueKey: {
  118. type: String,
  119. default: ''
  120. }
  121. },
  122. data() {
  123. return {
  124. secNum: this.seconds,
  125. timer: null,
  126. canGetCode: true, // 是否可以执行验证码操作
  127. tips: '',
  128. locale:{}, // 语言
  129. };
  130. },
  131. created(){
  132. if (typeof vk !== "undefined") {
  133. let locale = vk.pubfn.getLocale();
  134. this.locale = localeObj[locale];
  135. } else {
  136. this.locale = localeObj["zh-Hans"];
  137. }
  138. },
  139. mounted() {
  140. this.checkKeepRunning();
  141. },
  142. watch: {
  143. seconds: {
  144. immediate: true,
  145. handler(n) {
  146. this.secNum = n;
  147. }
  148. }
  149. },
  150. // 计算属性
  151. computed:{
  152. startTextCom(){
  153. return this.startText || this.locale.startText || "获取验证码";
  154. },
  155. changeTextCom(){
  156. return this.changeText || this.locale.changeText || "X秒重新获取";
  157. },
  158. endTextCom(){
  159. return this.endText || this.locale.endText || "重新获取";
  160. }
  161. },
  162. methods: {
  163. checkKeepRunning() {
  164. // 获取上一次退出页面(H5还包括刷新)时的时间戳,如果没有上次的保存,此值可能为空
  165. let lastTimestamp = Number(uni.getStorageSync(this.uniqueKey + '_$uCountDownTimestamp'));
  166. if (!lastTimestamp) return this.changeEvent(this.startTextCom);
  167. // 当前秒的时间戳
  168. let nowTimestamp = Math.floor(+new Date() / 1000);
  169. // 判断当前的时间戳,是否小于上一次的本该按设定结束,却提前结束的时间戳
  170. if (this.keepRunning && lastTimestamp && lastTimestamp > nowTimestamp) {
  171. // 剩余尚未执行完的倒计秒数
  172. this.secNum = lastTimestamp - nowTimestamp;
  173. // 清除本地保存的变量
  174. uni.removeStorageSync(this.uniqueKey + '_$uCountDownTimestamp');
  175. // 开始倒计时
  176. this.start();
  177. } else {
  178. // 如果不存在需要继续上一次的倒计时,执行正常的逻辑
  179. this.changeEvent(this.startTextCom);
  180. }
  181. },
  182. // 开始倒计时
  183. start() {
  184. // 防止快速点击获取验证码的按钮而导致内部产生多个定时器导致混乱
  185. if (this.timer) {
  186. clearInterval(this.timer);
  187. this.timer = null;
  188. }
  189. this.$emit('start');
  190. this.canGetCode = false;
  191. // 这里放这句,是为了一开始时就提示,否则要等setInterval的1秒后才会有提示
  192. this.changeEvent(this.changeTextCom.replace(/x|X/, this.secNum));
  193. this.setTimeToStorage();
  194. this.timer = setInterval(() => {
  195. if (--this.secNum) {
  196. // 用当前倒计时的秒数替换提示字符串中的"x"字母
  197. this.changeEvent(this.changeTextCom.replace(/x|X/, this.secNum));
  198. } else {
  199. clearInterval(this.timer);
  200. this.timer = null;
  201. this.changeEvent(this.endTextCom);
  202. this.secNum = this.seconds;
  203. this.$emit('end');
  204. this.canGetCode = true;
  205. }
  206. }, 1000);
  207. },
  208. // 重置,可以让用户再次获取验证码
  209. reset(text) {
  210. this.canGetCode = true;
  211. clearInterval(this.timer);
  212. this.secNum = this.seconds;
  213. this.changeEvent(text || this.endTextCom);
  214. },
  215. changeEvent(text) {
  216. this.codeChange(text);
  217. this.$emit('change', text);
  218. },
  219. // 保存时间戳,为了防止倒计时尚未结束,H5刷新或者各端的右上角返回上一页再进来
  220. setTimeToStorage() {
  221. if (!this.keepRunning || !this.timer) return;
  222. // 记录当前的时间戳,为了下次进入页面,如果还在倒计时内的话,继续倒计时
  223. // 倒计时尚未结束,结果大于0;倒计时已经开始,就会小于初始值,如果等于初始值,说明没有开始倒计时,无需处理
  224. if (this.secNum > 0 && this.secNum <= this.seconds) {
  225. // 获取当前时间戳(+ new Date()为特殊写法),除以1000变成秒,再去除小数部分
  226. let nowTimestamp = Math.floor(+new Date() / 1000);
  227. // 将本该结束时候的时间戳保存起来 => 当前时间戳 + 剩余的秒数
  228. uni.setStorage({
  229. key: this.uniqueKey + '_$uCountDownTimestamp',
  230. data: nowTimestamp + Number(this.secNum)
  231. });
  232. }
  233. },
  234. // 倒计时进行时
  235. codeChange(text) {
  236. this.tips = text;
  237. this.$emit('codeChange', text);
  238. },
  239. // 发送短信验证码
  240. sendSmsCode() {
  241. let that = this;
  242. let vk = uni.vk;
  243. if (!that.canGetCode) {
  244. vk.toast(`${that.secNum}${that.locale.tryAgainInSeconds}`, 'none');
  245. return;
  246. }
  247. if (that.mode === "custom") {
  248. that.$emit("send", { type: that.type });
  249. return;
  250. }
  251. let mobile = that.mobile;
  252. let type = that.type;
  253. if (!vk.pubfn.test(mobile, 'mobile')) {
  254. vk.toast(that.locale.pleaseEnterTheCorrectMobileNumber, 'none');
  255. return;
  256. }
  257. that.tips = that.locale.sending;
  258. vk.userCenter.sendSmsCode({
  259. needAlert: false,
  260. data: {
  261. mobile,
  262. type
  263. },
  264. success: function(data) {
  265. vk.toast(that.locale.verificationCodeSent);
  266. that.start();
  267. },
  268. fail: function(err) {
  269. that.tips = that.startTextCom;
  270. if (err.errMsg && err.errMsg.indexOf('触发天级流控') > -1) {
  271. vk.alert(that.locale.pleaseTryAgainTomorrow);
  272. } else if (err.errMsg && err.errMsg.indexOf('触发小时级流控') > -1) {
  273. vk.alert(that.locale.pleaseTryAgainIn1Hour);
  274. } else if (err.errMsg && err.errMsg.indexOf('触发分钟级流控') > -1) {
  275. vk.alert(that.locale.pleaseTryAgainLater);
  276. } else if (err.msg) {
  277. vk.alert(err.msg);
  278. } else {
  279. vk.alert(that.locale.pleaseTryAgainLater);
  280. }
  281. }
  282. });
  283. }
  284. },
  285. // 组件销毁的时候,清除定时器,否则定时器会继续存在,系统不会自动清除
  286. // #ifndef VUE3
  287. beforeDestroy() {
  288. this.setTimeToStorage();
  289. clearTimeout(this.timer);
  290. this.timer = null;
  291. },
  292. // #endif
  293. // #ifdef VUE3
  294. beforeUnmount() {
  295. this.setTimeToStorage();
  296. clearTimeout(this.timer);
  297. this.timer = null;
  298. }
  299. // #endif
  300. };
  301. </script>
  302. <style lang="scss" scoped></style>