仅在特定页面加载 nuxt 3 插件

问题描述 投票:0回答:1

我有一个 nuxt3 应用程序,我想将验证码添加到注册表单中。

我正在使用

vue-recaptcha-v3
包,就像
plugins/google-recaptcha.ts
中这样:

import { VueReCaptcha } from 'vue-recaptcha-v3';

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig();

  nuxtApp.vueApp.use(VueReCaptcha, {
    siteKey: config.public.recaptchaKey,
    loaderOptions: {
      autoHideBadge: false,
      explicitRenderParameters: {
        badge: 'bottomleft'
      }
    }
  });
});

问题是我希望插件只加载在注册页面上,而不是其他地方。有什么办法可以做到这一点吗?

nuxt.js nuxt3.js
1个回答
0
投票

要将 recaptcha 与 Nuxt3 一起使用并按需(而非全局)加载脚本,您可以使用此可组合项:

import { load } from 'recaptcha-v3'

export const useGoogleRecaptcha = () => {
    const getRecaptchaToken = async (action: string) => {
        const config = useRuntimeConfig()
        const recaptcha = await load(config.public.reCapatcha.apiKey, {
            autoHideBadge: true,
            useRecaptchaNet: true
        })
        const token = await recaptcha.execute(action)
        return token
    }

    return { getRecaptchaToken }
}

它利用了 recaptcha-v3 包(

vue-recaptcha-v3
也使用了该包)。加载和令牌生成是在一个函数调用中完成的,您可以在任何您想要的地方(例如在表单的提交函数中),而无需全局加载任何内容。

当然你需要安装这个包:

pnpm add -D add recaptcha-v3
© www.soinside.com 2019 - 2024. All rights reserved.