Use Google Recaptcha in Vue Forms

Google recaptcha is quite a powerful tool in reducing spam through our contact forms.

Once included in our forms, reCaptcha automatically manages suspicious activity, prompts additional ‘bot vs. human checks’, or is completely transparent to the overall flow - depending on who is interacting with the site.

Including reCaptcha in Vue is quite simple.

1. Install vue-recaptcha-v3

Install the NPM package called ‘vue-recaptcha-v3’. This will enable us to just plug and play recaptcha rather than including the 4-5 lines of code provided by Google.

2. Create the contact form

Create the Vue SFC that will house the contact form. Link to the form from the home page. An example with Vuetify is below.

<!-- Contact.vue -->

  <v-form ref="form" v-model="valid">
      <v-flex xs12>
        <span class="display-2">Contact Us</span>

      <v-flex xs12>
      <v-flex xs12>
      <v-flex xs12 offset-md6 md6 text-xs-right>
        <v-btn color="primary" @click="validateAndSubmit">Submit</v-btn>
3. Include reCaptcha code

Code the logic for the submit button and embed reCaptcha functionality therein.

<!-- Contact.vue -->

  import Vue from "vue";
  import { VueReCaptcha } from "vue-recaptcha-v3";
  Vue.use(VueReCaptcha, { siteKey: "your-google-recaptcha-site-key" });
  export default {
    data() {
      return {
        valid: true,
        contactDetail: { email: "", message: "" }
    methods: {
      validateAndSubmit() {
        if (this.$refs.form.validate()) {
          this.disableSubmit = true;
          this.$recaptcha("contactus").then(token => {
            // parse & store data. Method can be housed in Vuex store
            // show confirmation message

            // navigate to home page after processing  data
The End Result

You now have a beautiful form that will not only apply your own validations for the form, but also checks whether reCaptcha is happy before submitting data to your back-end.

comments powered by Disqus