Подтвердить что ты не робот

Vue.js Google ReCaptcha обратный вызов

Я пытаюсь получить обратный вызов recaptcha, работающий с vue.js в компоненте. Сама капча работает, но не обратный вызов, который я определяю в атрибуте 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 функций не dothisthat. Что я делаю неправильно?

4b9b3361

Ответ 1

Я тоже столкнулся с этой проблемой, и мне потребовалось 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>

Ответ 2

Я не использую компонент, но у меня была та же проблема, и, наконец, я разрешаю его следующим образом:

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);
    }
},

Ответ 3

Если вы ищете только значение ответа recaptcha для проверки его на стороне сервера, простое решение - поместить ваш элемент recaptcha в форму и получить значение ответа из целевого элемента event submit.

<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

           ...
         }

Ответ 4

Проблема, с которой я столкнулся в других решениях, заключается в том, что он иногда пытается выполнить window.grecaptcha.render когда ReCaptcha не загружен полностью. Единственный способ проверить это согласно их документации - использовать метод 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" />