簡體   English   中英

ReCaptcha v2 不會在 vue-router 導航中加載

[英]ReCaptcha v2 won't load in vue-router navigation

我正在使用 Google ReCaptcha v2,我正在將它集成到注冊過程中。 因此,當用戶訪問/register ,它會加載RegisterComponent

但是,當我在主頁中並通過按鈕導航到/register時,不會加載 reCaptcha。 為什么會發生?

我正在layouts.master.php加載腳本:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

並在注冊組件中加載 reCaptcha,如下所示:

<div class="field">
    <div class="control" id="recaptcha-reg">
        <div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></div>
        <span v-if="regErrors.captcha" v-for="error in errors">{{ error }}</span>
    </div>
</div>

然后使用 PHP 驗證此 reCaptcha。 所以,沒有 JS 邏輯! 請幫忙!

如果有人遇到同樣的問題,以下是解決方法:

  • 將 id 分配給您的 reCaptcha 小部件。
  • 然后在創建組件時,運行setTimeout來呈現小部件。

例子:

<div id="recaptcha-main" class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></div>

然后在您要加載驗證碼的組件中:

created() {
    setTimeout(() => {
        grecaptcha.render('recaptcha-main'); // 'recaptcha-main' is the id that was assigned to the widget
    }, 2000);
}

就是這樣!

更新 - 最好的方法

而不是使用setTimeout ,而是使用nextTick()代替它基本上只在視圖包括之后運行。 孩子們完成了裝載。

您分配 id,然后在您created鈎子中運行它:

this.$nextTick(function () {
    grecaptcha.render('recaptcha-main');
})

setTimeout的缺點是它只在指定的時間之后運行。 例如說 1 秒。 因此,如果您的組件需要 1 秒以上才能完全加載,那么setTimeout在這里可能不起作用,因為它將在 1 秒后立即執行。

我希望這對你有用:)

@Damon 的回答有效並且很棒 - 我想我只是發布一些 vue 組件代碼來幫助其他人實現它:

created() { // in whatever component has a recaptcha
    window.sendMsg = this.sendMsg // making the callback function from the vue object available to the google script in the global scope.
    console.log('grecaptcha', grecaptcha)
    this.$nextTick(function() {
        grecaptcha.ready(function() { // making sure the recapcha script is loaded
            try {
                grecaptcha.render('invisibleRecaptcha1') //render the plain-jane recaptcha element with the given id
            } catch (err) { // dont care about errors, because the worst that can happen is maybe it already rendered once.
                err
            }
        })
    })
}

這個想法只是你應該像往常一樣把 google script 標簽放在head中,然后使用最簡單的靜態集成標簽:

<button id="invisibleRecaptcha1" class="g-recaptcha" data-sitekey="6Lc7hdkZ**********************" data-callback="sendMsg" data-action="submit">Shout!</button>

其中sendMsg是您使用recaptcha 保護的任何功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM