一个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>