# Nuxt 實作 Google reCAPTCHA / Google 非機器人驗證 **此為學習/紀錄筆記,有錯誤歡迎告知!** ## 前言 去年在公司有個需求是先去研究Vue連接Google Recaptcha,也有寫了一篇簡單的文章[在這邊](https://hackmd.io/ftgjGkmmTPuwetzJTy3xJw)。現在需要把他實作進去Nuxt3的架構,而且有一個特別的需求,就是Google Rechptcha的Site Key要等API回傳後,再丟入,這是一個比較麻煩的需求。 ``` Typescript /plugins/google-recapcha.ts /** src/plugins/google-recapcha.ts */ import { VueReCaptcha } from 'vue-recaptcha-v3'; export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(VueReCaptcha, { siteKey: '<SITE_KEY>', loaderOptions: { autoHideBadge: false, explicitRenderParameters: { badge: 'bottomright', }, }, }); }); ``` 一般Nuxt3註冊`vue-recaptcha-v3`會寫一個`plugin`,並從`NuxtConfig`拿出你的`SITE_KEY`進行註冊,就像上面的程式碼一樣。但目前的目標要等後端API的回傳,其中有一個就是`SITE_KEY`再進行註冊,所以才有今天這篇文章~ ## Install vue-recaptcha-v3 運用你熟悉的就可以了: ``` BASH npm install vue-recaptcha-v3 yarn add vue-recaptcha-v3 ``` ## 定義Composable去處理 因為`SITE_KEY`會從後端API回傳,所以可以定義一個function有一個參數是`SITE_KEY`: ``` Typescript /composables/useGoogleRecaptcha/index.ts /** src/composables/useGoogleRecaptcha/index.ts */ import { VueReCaptcha } from 'vue-recaptcha-v3'; export function function_useRecaptchaInit (data_siteKey: string) { const { vueApp } = useNuxtApp(); vueApp.use(VueReCaptcha, { siteKey: data_siteKey, loaderOptions: { autoHideBadge: true }, }); } ``` 其實就是將`plugins`的內容包成composable,在需要的時候取用。 一樣要去注意,`vue-recaptcha-v3`有定義到`IReCaptchaComposition`(其實就是`ReCaptchaInstance`跟他擁有的方法集合)的都要在`setup`**生命週期**中使用。 這樣舊註冊好`SITE_KEY`,接下來就可以依照你喜歡的去封裝,給使用端操作了! ## 封裝Composable給使用端 要注意的點有兩個點: 1. 所有有定義到`IReCaptchaComposition`都要在`setup`**生命週期**中使用。 2. 因為Nuxt3是預設Typescript,所以要檢查Recaptcha是不是`undefined`。 上述兩點只要保持你是在`Client Side`註冊你的`SITE_KEY`,而且是在`setup`**生命週期**中使用,且使用前有做`undefined check`,就沒問題了。 ``` Typescript /composables/useGoogleRecaptcha/index.ts /** src/composables/useGoogleRecaptcha/index.ts */ import { VueReCaptcha, useReCaptcha, type IReCaptchaComposition } from 'vue-recaptcha-v3'; export const function_getGoogleRecaptchaInstance = () => useReCaptcha(); export const function_useRecaptchaByInstance = async (data_instance: IReCaptchaComposition | undefined) => { if (data_instance) { await data_instance.recaptchaLoaded(); return await data_instance.executeRecaptcha('login'); } return ''; }; ``` 上述的code是參考,一定有更好的封裝方式,只是小弟我目前功力尚淺,思路如下: 1. `function_getGoogleRecaptchaInstance`用來在`setup`**生命週期**取得實例,他有當前的型別會是:`IReCaptchaComposition | undefined` 2. `function_useRecaptchaByInstance`將實例傳入,做`undefined`的判斷,是`undefined`的話可以做錯誤處理(我是回傳空字串);反之,處理Recaptcha的行為,這個方法可以多傳入一個參數(string)去由外部控制Recaptcha的行為('login')。 因為實例是在`setup`**生命週期**取得的,所以沒有跳脫生命周期的限制,且方法有去確保實例不是`undefined`,就不會出問題。封裝方式百百種,可以依照你的需求去封裝。 *如本文章有問題歡迎留言告知,感謝~*
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up