Vue.js google reCaptcha回调

问题描述 投票:13回答:5

我试图在组件中使用vue.js进行recaptcha回调。验证码本身确实有效,但不是我在data-callback属性中定义的回调。

我已经尝试了我能想到的一切,但我仍然得到ReCAPTCHA couldn't find user-provided function: dothisthat错误。

这是组件

<script>
    function dothisthat (){
            alert(312);
        }
</script>

<template>
    <div class="well main-well">
        <h4>Captcha</h4>
        <p class="small">You must complete the captcha to finish your booking.</p>
        <div id="captcha-wrapper">
            <div class="g-recaptcha" :data-sitekey="captchaKey" data-callback="dothisthat"></div>
        </div>
    </div>
</template>
<script>
     function dothisthat (){
        alert(123);
    }
    import * as filters from '../../../filters';
    import Translation from '../../../Translation';

    export default {
        name: 'Captcha',
        props: {
        },
        computed: {
            captchaKey: function() {
                return this.$store.getters.captcha;
            }
        },
        methods: {
            dothisthat: function(){
                return function() {
                    console.log("123");
                };
            }
        },
        mounted(){

            function dothisthat() {
                alert(123);
            }
            $(function() {
                function dothisthat() {
                    alert(123);
                }
            });
        }
    }
</script>

没有一个dothisthat函数被调用。我究竟做错了什么?

javascript vue.js recaptcha
5个回答
17
投票

我也遇到了这个问题,我花了2天才解决它。

所以我将在这里提供一个一般性的答案,用于逐步将recaptcha与vue.js从头开始集成,以便成为将来处于相同情况的人们的简单指南(我假设这里使用了vue-cli)。

注意:我在这里使用隐形recaptcha,但过程非常类似于正常的过程

步骤1:

将recaptcha javascript api添加到index.html

的index.html

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

第2步:

创建一个名为Recaptcha的组件或任何你想要它的组件(如果你需要,组件将使你的代码更容易阅读,更容易维护,更容易将recaptcha添加到多个页面)

Recaptcha.vue

<template>
  <div 
  id="g-recaptcha"
  class="g-recaptcha"
  :data-sitekey="sitekey">
  </div>
</template>

<script>
export default {
  data () {
    return {
      sitekey: '6LfAEj0UAAAAAFTGLqGozrRD8ayOy*********',
      widgetId: 0
    }
  },
  methods: {
    execute () {
      window.grecaptcha.execute(this.widgetId)
    },
    reset () {
      window.grecaptcha.reset(this.widgetId)
    },
    render () {
      if (window.grecaptcha) {
        this.widgetId = window.grecaptcha.render('g-recaptcha', {
          sitekey: this.sitekey,
          size: 'invisible',
          // the callback executed when the user solve the recaptcha
          callback: (response) => {
            // emit an event called verify with the response as payload
            this.$emit('verify', response)
            // reset the recaptcha widget so you can execute it again
            this.reset() 
          }
        })
      }
    }
  },
  mounted () {
    // render the recaptcha widget when the component is mounted
    this.render()
  }
}
</script>

第3步:

导入recaptcha组件并将其添加到页面(父组件)。

page.vue

<template>
  <div>
    <h1>Parent component (your page)</h1>
    <button @click="executeRecaptcha">execute recaptcha</button>
    <!-- listen to verify event emited by the recaptcha component -->
    <recaptcha ref="recaptcha" @verify="submit"></recaptcha>
  </div>
</template>

<script>
import Recaptcha from 'recaptcha'
export default {
  components: {
    Recaptcha
  },
  methods: {
    // send your recaptcha token to the server to verify it
    submit (response) {
      console.log(response)
    },
    // execute the recaptcha widget
    executeRecaptcha () {
      this.$refs.recaptcha.execute()
    }
  }
}
</script>

14
投票

我没有使用组件,但我遇到了同样的问题,最后我解决了这个问题:

HTML

<div id="recaptcha" class="g-recaptcha"></div>
<button id="submit" @click="validate">Submit</button>
<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>

JS

// ...
mounted: function() {
    this.initReCaptcha();
},
methods: {
    initReCaptcha: function() {
        var self = this;
        setTimeout(function() {
            if(typeof grecaptcha === 'undefined') {
                self.initReCaptcha();
            }
            else {
                grecaptcha.render('recaptcha', {
                    sitekey: 'SITE_KEY',
                    size: 'invisible',
                    badge: 'inline',
                    callback: self.submit
                });
            }
        }, 100);
    },
    validate: function() {
        // your validations...
        // ...
        grecaptcha.execute();
    },
    submit: function(token) {
        console.log(token);
    }
},

2
投票

如果您只是在查找recaptcha的响应值以便在服务器端验证它,一个简单的解决方案是将您的recaptcha元素放在一个表单中,并从submit event的target元素中获取响应值。

<form class="container"
  @submit="checkForm"
  method="post"
>

... // other elements of your form 

<div class="g-recaptcha" data-sitekey="your_site_key"></div>

<p>
    <input class="button" type="submit" value="Submit">
</p>
</form>

并在checkForm方法:

methods : {
        checkForm: function (event) {
            recaptcha_response_value = event.target['g-recaptcha-response'].value

           ...
         }

0
投票

我对其他解决方案的问题在于,当ReCaptcha未完全加载时,它有时会尝试执行window.grecaptcha.render。根据他们的documentation检查的唯一方法是使用onload方法。

下面这个例子就是我如何使用它,当然你可以自定义你使用回调做的事情。

ReCaptcha.Vue:

<template>
    <div ref="grecaptcha"></div>
</template>

<script>
    export default {

        props: ['sitekey'],

        methods: {

            loaded(){

                window.grecaptcha.render(this.$refs.grecaptcha, {
                    sitekey: this.sitekey,
                    callback: (response) => {

                        this.$emit('input', response);

                    },
                });

            },

        },

        mounted(){

            /**
             * Set Recapchat loaded function
             */
            window.ReCaptchaLoaded = this.loaded;

            /**
             * Set Recaptcha script in header
             */
            var script = document.createElement('script');
            script.src = 'https://www.google.com/recaptcha/api.js?onload=ReCaptchaLoaded&render=explicit';
            document.head.appendChild(script);

        }

    }
</script>

用法:

<ReCaptcha sitekey="KEY" v-model="fields.g_recaptcha_response.value" />

0
投票
in Vue Component : 

在模板中:html

<template>
<form @submit.prevent="onSubmit">
    <div class="form-group row">
        <label for="email" class="col-sm-4 col-form-label text-md-right">Email : </label>

        <div class="col-md-6">
            <input v-model="email" id="email"  type="email" class="form-control"  value="" required autofocus>


            <span class="invalid-feedback" role="alert">
                                    <strong></strong>
                                </span>

        </div>
    </div>

    <div class="form-group row">
        <label for="password" class="col-md-4 col-form-label text-md-right">
            Password :
        </label>

        <div class="col-md-6">
            <input v-model="password" id="password" type="password" class="form-control"  required>


            <span class="invalid-feedback" role="alert">
                                    <strong></strong>
                                </span>

        </div>
    </div>

    <div class="form-group row">
        <div class="col-md-6 offset-md-4">
            <div class="form-check">

                <input class="form-check-input" type="checkbox" id="remember" v-model="remember">

                <label class="form-check-label" for="remember">
                   Remember me
                </label>
                <div id="recaptcha" class="g-recaptcha" data-sitekey="6LehfpsUAAAAAIf3hvWNrGvat8o4lypZh_p6snRH"></div>
            </div>
        </div>
    </div>

    <div class="form-group row mb-0">
        <div class="col-md-8 offset-md-4">
            <a href="" class="btn btn-danger">Login with google</a>
            <button type="submit" class="btn btn-primary">
                Login
            </button>

            <a class="btn btn-link" href="">
                Forgot Your Password?
            </a>
        </div>
    </div>
</form>

和javascript:

<script>
import swal from 'sweetalert';
export default {
   data(){

       return {
           email: '',
           password: '',
           remember: ''
       }

   },
    mounted: function() {
        this.initReCaptcha();
    },
    methods: {
        onSubmit(event) {

            let recaptcha_response_value = event.target['g-recaptcha-response'].value;
            console.log(recaptcha_response_value);
            let formData = new FormData();
            formData.append('email' , this.email);
            formData.append('password' , this.password);
            formData.append('remember' , this.remember);
            formData.append('g-recaptcha-response' , recaptcha_response_value);
            axios.post('/login' , formData)
                .then(
                    function(res){
                        swal('ورود شما موفقیت آمیز بود');
                    }
                )
                .catch(function(err){
                    swal('ایمیل یا کلمه عبور اشتباه است یا اینکه هنوز ثبت نام نکرده اید');
                    console.log(err);
                });

        }
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.