Follow

一个Vue3 的reCaptcha组件

<template>
  <div class="recaptcha__container">
    <div
      class="g-recaptcha"
      :data-sitekey="sitekey"
      :data-theme="theme"
      data-size="normal"
      :ref="setGRef"
    ></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, watch, onMounted, onUnmounted } from "vue";
import { useElementRef, useState } from "@/hooks";
import camelcaseKeys from "camelcase-keys";

export default defineComponent({
  emits: ["verified"],
  setup(props, { emit }) {
    const sitekey = "recaptchaSiteKey";
    const theme = "light"; // dark
    const [gRef, setGRef] = useElementRef();
    const [idRef, setIdRef] = useState(NaN);
    const [tokenRef, setTokenRef] = useState("");

    watch(gRef, (gEl) => {
      if (gEl) {
        setIdRef(grecaptcha.render(gEl, { sitekey, theme }));
      }
    });

    onMounted(() => {
      let timer = setInterval(() => {
        try {
          setTokenRef(grecaptcha.getResponse(idRef.value));
        } catch (e) {}
        if (tokenRef.value) {
          clearInterval(timer);
        }
      }, 1000);

      onUnmounted(() => {
        clearInterval(timer);
      });
    });

    watch(tokenRef, (token) => {
      console.log(token);
      emit("verified", token);
    });

    return { sitekey,theme, setGRef };
  },
});
</script>
· · Web · 0 · 0 · 1
Sign in to participate in the conversation
小森林

每个人都有属于自己的一片森林,也许我们从来不曾走过,但它一直在那里,总会在那里。迷失的人迷失了,相逢的人会再相逢。愿这里,成为属于你的小森林。