recaptcha在Vue组件中不起作用。当未加载grecaptcha时,给grecaptcha.render不是一个函数

Ahm*_*et 2 javascript recaptcha vue.js

如何在Vue组件中添加grecaptcha onload方法。未加载时grecaptcha.render不是函数

const script = document.createElement("script");
 script.src = `${URL}?render=explicit&hl=TR`;
 script.async = true;
 script.defer = true;
 document.body.appendChild(script);
 this.initReCaptcha();


initReCaptcha: function () {
    setTimeout(function () {
       if (typeof grecaptcha === 'undefined') {
           this.initReCaptcha();
       } else {
          grecaptcha.render('recaptcha', {
          sitekey: 'XXXX',
          callback: this.submit,
          'expired-callback': this.expired
                        });
                    }
                }.bind(this), 100);
            }
Run Code Online (Sandbox Code Playgroud)

我将超时设置为1000时正在工作,但为时已晚。

小智 6

Recaptcha脚本已于格林尼治标准时间2018年5月4日晚上9:07:30.349更新(基于Recaptcha脚本的时间戳)。正在加载grecaptcha,但是render函数有一个延迟,这就是为什么recaptcha不在UI中显示的原因(grecaptcha.render不是功能)。可能的解决方法是在尝试加载Recaptcha之前验证渲染功能。

解决方法是:

initReCaptcha: function () {
    setTimeout(function () {
       if (typeof grecaptcha === 'undefined' && typeof grecaptcha.render ==='undefined') {
           this.initReCaptcha();
       } else {
          grecaptcha.render('recaptcha', {
          sitekey: 'XXXX',
          callback: this.submit,
          'expired-callback': this.expired
                        });
                    }
                }.bind(this), 100);
            }
Run Code Online (Sandbox Code Playgroud)

希望对您有帮助。干杯