如何在Nuxt 3中正确实现Google reCAPTCHA?路由跳转加载异常求助
问题解决:Nuxt路由跳转后Google reCAPTCHA无法加载
问题说明
使用router.push("/dashboard")或NuxtLink跳转页面后,Dashboard页面中的Google reCAPTCHA无法正常显示,必须手动刷新页面才能加载成功。
问题根源
Nuxt是单页应用(SPA),路由跳转时不会重新加载整个页面。你在nuxt.config.ts中引入的reCAPTCHA脚本仅会在页面首次加载时自动扫描带有g-recaptcha类的元素并完成渲染。路由跳转后新增的DOM元素不会被脚本自动检测到,因此reCAPTCHA无法自动初始化。
解决方案:手动初始化reCAPTCHA
放弃依赖脚本自动渲染,改用grecaptcha.render()方法手动初始化reCAPTCHA,修改Dashboard页面代码如下:
修改后的Dashboard页面代码
<template> <div> <h1>Dashboard</h1> <!-- 用ID定位容器,比class定位更精准 --> <div id="recaptcha-container"></div> <NuxtLink to="/painel">返回面板</NuxtLink><br> </div> </template> <script setup> import { onMounted } from 'vue' onMounted(() => { // 确保reCAPTCHA脚本加载完成后手动渲染 if (window.grecaptcha) { window.grecaptcha.render('recaptcha-container', { sitekey: '6LedcrYoAAAAAKcf9pvM5x11DXBi1Ik5oke8qQ0v' }) } else { // 处理脚本加载延迟的情况 const recaptchaScript = document.querySelector('script[src="https://www.google.com/recaptcha/api.js"]') if (recaptchaScript) { recaptchaScript.onload = () => { window.grecaptcha.render('recaptcha-container', { sitekey: '6LedcrYoAAAAAKcf9pvM5x11DXBi1Ik5oke8qQ0v' }) } } } }) </script>
可选:封装成可复用组件
如果多个页面需要使用reCAPTCHA,可以封装成组件,方便复用同时避免内存泄漏:
创建components/Recaptcha.vue
<template> <div :id="uniqueId"></div> </template> <script setup> import { ref, onMounted, onBeforeUnmount } from 'vue' const props = defineProps({ sitekey: { type: String, required: true } }) // 生成唯一ID,避免多个组件冲突 const uniqueId = ref(`recaptcha-${Math.random().toString(36).slice(2)}`) let widgetId = null onMounted(() => { if (window.grecaptcha) { widgetId = window.grecaptcha.render(uniqueId.value, { sitekey: props.sitekey }) } }) onBeforeUnmount(() => { // 组件卸载时重置实例,释放资源 if (window.grecaptcha && widgetId) { window.grecaptcha.reset(widgetId) } }) </script>
在Dashboard页面使用组件
<template> <div> <h1>Dashboard</h1> <Recaptcha sitekey="6LedcrYoAAAAAKcf9pvM5x11DXBi1Ik5oke8qQ0v" /> <NuxtLink to="/painel">返回面板</NuxtLink><br> </div> </template>
内容的提问来源于stack exchange,提问作者Henrique
相关产品推荐
相关产品推荐

