You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt 3中实现Google reCAPTCHA V2?已遇两类问题

Nuxt 3 集成 Google reCAPTCHA 问题与解决方案

我在 Nuxt 应用中尝试集成 Google reCAPTCHA,当前使用版本为 "nuxt": "3.0.0-rc.11"。尝试使用 Nuxt2 或 Vue3 的 reCAPTCHA 库均出现错误,于是自行实现了一套方案,具体代码如下:

模板代码

<template>
  <form
    action="?"
    class="mt-8"
    method="POST"
  >
    <div id="g-recaptcha"></div>
  </form>
</template>

脚本代码

<script setup lang="ts">
useHead({
    title: 'Contact',
    titleTemplate: 'Gears - %s',
    viewport: 'width=device-width, initial-scale=1, maximum-scale=1',
    charset: 'utf-8',
    meta: [
        {name: 'description', content: 'Let’s discuss your work together.'}
    ],
    // 通过 useHead() 注入 reCaptcha 脚本
    script: [
        {
            hid: 'recaptcha',
            src: 'https://www.google.com/recaptcha/api.js?trustedtypes=true?onload=onloadCallback&render=explicit',
            defer: true
        }
    ]
})

const isRecaptchaChecked = ref(false)
const form = reactive({
   token: ''
})

function recaptchaCallback(token) {
    isRecaptchaChecked.value = grecaptcha && grecaptcha.getResponse().length !== 0;
    if (isRecaptchaChecked.value) {
        form.token = token
    }
}

onMounted(async () => {
    await grecaptcha.render('g-recaptcha', {
        'sitekey': runtimeConfig.siteKey,
        'callback': recaptchaCallback
    });
})
</script>

存在的问题

  • 初始加载时会报错 ReferenceError: grecaptcha is not defined,刷新页面后功能恢复正常且能生成token;
  • 完成reCAPTCHA验证后,页面路由(如从/contact跳转至/home)在浏览器地址栏变化,但页面未更新。

补充说明

@nuxtjs/recaptcha 暂不兼容 Nuxt3,待其支持后建议使用 @nuxt-recaptcha 包。我已找到对应的解决方案。

内容的提问来源于stack exchange,提问作者Waleed Tariq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:15:35