index.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <template>
  2. <SlideCaptcha
  3. ref="slideCaptchaRef"
  4. :fail-tip="state.failTip"
  5. :success-tip="state.successTip"
  6. width="100%"
  7. height="auto"
  8. @refresh="onGenerate"
  9. @finish="onFinish"
  10. v-bind="$attrs"
  11. />
  12. </template>
  13. <script lang="ts" setup name="my-captcha">
  14. import { defineAsyncComponent, ref, reactive } from 'vue'
  15. import { CaptchaApi } from '/@/api/admin/Captcha'
  16. const emits = defineEmits(['ok'])
  17. const SlideCaptcha = defineAsyncComponent(() => import('./slide-captcha.vue'))
  18. const slideCaptchaRef = ref()
  19. const state = reactive({
  20. requestId: '',
  21. failTip: '',
  22. successTip: '',
  23. })
  24. //生成滑块验证码
  25. const onGenerate = async () => {
  26. slideCaptchaRef.value.startRequestGenerate()
  27. const res = await new CaptchaApi().generate({ captchaId: state.requestId }).catch(() => {
  28. slideCaptchaRef.value.endRequestGenerate(null, null)
  29. })
  30. if (res?.success && res.data) {
  31. state.requestId = res.data.id || ''
  32. slideCaptchaRef.value.endRequestGenerate(res.data.backgroundImage, res.data.sliderImage)
  33. }
  34. }
  35. //验证滑块验证码
  36. const onFinish = async (data: any) => {
  37. slideCaptchaRef.value.startRequestVerify()
  38. const res = await new CaptchaApi().check(data, { captchaId: state.requestId }).catch(() => {
  39. state.failTip = '服务异常,请稍后重试'
  40. slideCaptchaRef.value.endRequestVerify(false)
  41. })
  42. if (res?.success && res.data) {
  43. let success = res.data.result === 0
  44. state.failTip = res.data.result == 1 ? '验证未通过,拖动滑块将悬浮图像正确合并' : '验证超时, 请重新操作'
  45. state.successTip = '验证通过'
  46. slideCaptchaRef.value.endRequestVerify(success)
  47. if (success) {
  48. //验证成功
  49. emits('ok', { captchaId: state.requestId, captchaData: data })
  50. } else {
  51. setTimeout(() => {
  52. onGenerate()
  53. }, 1000)
  54. }
  55. }
  56. }
  57. //刷新滑块验证码
  58. const refresh = () => {
  59. slideCaptchaRef.value?.handleRefresh()
  60. }
  61. defineExpose({
  62. refresh,
  63. })
  64. </script>
  65. <style scoped lang="scss"></style>