Vue Contact Form

Without Backend, Sent via Email (or Slack)

Forms Example

This guide will show you how to make a nice-looking and elegant form with Vue. Contact form creation in Vue shouldn't be a tedious task if you're working on a static/jamstack site.

Often, different guides suggest using backend NodeJS/PHP servers for storing/emailing data. But it's not an absolute rule if you think smart, and your codebase can be a lot cleaner with the fronted-only code.

Create the Vue app

(if you're starting a brand new project)

In case you're starting a brand new project, you'll need some initial steps. One of the most straightforward ways is to use the create-vue-app package. To start:

  • Open the terminal and install the create-vue-app package
    npm install @vue/cli --global
  • Then create your app; this will be your project root folder
    vue create vue-project
  • Go to the directory where you will store your project
    cd ~/vue-project
  • When the installation has finished, you can start the server
    npm run serve

Use your favorite code editor to work with files in ~/vue-project/src. You will be able to make a contact form there.

Please keep in mind that the TailwindCSS example is for demo purposes only, for the production please refer to the TailwindCSS installation.

Embed component into your app, enable styling

Open App.vue in your src folder.

<template>
  <div class="app-advanced p-10">
    <img class="mx-auto" alt="Vue logo" src="../assets/logo.png" />

    <form
      :action="FORM_ENDPOINT"
      @submit="handleSubmit"
      method="POST"
      class="w-1/2 mx-auto mt-5"
    >
      <div class="mb-3 pt-0">
        <input
          type="text"
          placeholder="Your name"
          name="name"
          class="
            px-3
            py-3
            placeholder-gray-400
            text-gray-600
            relative
            bg-white bg-white
            rounded
            text-sm
            border-0
            shadow
            outline-none
            focus:outline-none
            focus:ring
            w-full
          "
          required
        />
      </div>

      <div class="mb-3 pt-0">
        <input
          type="email"
          placeholder="Email"
          name="email"
          class="
            px-3
            py-3
            placeholder-gray-400
            text-gray-600
            relative
            bg-white bg-white
            rounded
            text-sm
            border-0
            shadow
            outline-none
            focus:outline-none
            focus:ring
            w-full
          "
          required
        />
      </div>

      <div class="mb-3 pt-0">
        <textarea
          placeholder="Your message"
          name="message"
          class="
            px-3
            py-3
            placeholder-gray-400
            text-gray-600
            relative
            bg-white bg-white
            rounded
            text-sm
            border-0
            shadow
            outline-none
            focus:outline-none
            focus:ring
            w-full
          "
          required
        />
      </div>

      <div class="mb-3 pt-0">
        <button
          class="
            bg-blue-500
            text-white
            active:bg-blue-600
            font-bold
            uppercase
            text-sm
            px-6
            py-3
            rounded
            shadow
            hover:shadow-lg
            outline-none
            focus:outline-none
            mr-1
            mb-1
            ease-linear
            transition-all
            duration-150
          "
          type="submit"
        >
          Send a message
        </button>
      </div>
    </form>

    <div v-if="submitted" class="text-center mt-10">
      <h2 class="text-2xl">Thanks you!</h2>
      <div class="text-md">We'll be in touch soon.</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    submitted: false,
    FORM_ENDPOINT: endpointUrl,
  }),

  methods: {
    handleSubmit() {
      setTimeout(() => {
        this.submitted = true;
      }, 100);
    },
  },

  // To Add Tailwind
  beforeCreate() {
    if (document) {
      const stylesheet = document.createElement("link");
      stylesheet.rel = "stylesheet";
      stylesheet.href =
        "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css";

      document.head.appendChild(stylesheet);
    }
  },
};
</script>

Create the free HeroTofu forms backend

Head over to herotofu.com and create an account. It will handle all the boring and complex form submission process work for you. You'll get 14 days of the free trial at first, and later you can leave it with the free forever plan. For the sole purpose of the contact form, it's usually more than enough.

HeroTofu registration is straightforward. Fill in the basic fields and then confirm your email address.

Herotofu signup

Once you have confirmed your email address, go to app.herotofu.com/forms to create your first form. Fill in the form name and add your preferred email address where you'd like to receive your form submits. Slack and Zapier are also options, but you need to pay for them once the trial is over.

You'll get the form endpoint URL once you hit submit, so remember to copy it.

Herotofu Forms List

Use the created forms backend in your contact form

Once again, open the App.vue file and fill in the form endpoint URL. You need to change the FORM_ENDPOINT variable.

Done! Go ahead and test your contact form submission! You don't need to do any backend email work, as HeroTofu will handle everything.

Bonus: advanced Vue implementation

As you can see, the implementation is basic, and you only get those fields on the contact form that are visible on the HTML. That might not work if you need a more customized flow. You'll need to adjust the handleSubmit handler function to inject extra data dynamically. Good examples could be the user id, the selected plan, or some meta-information of site usage. It should make an ajax call to the FORM_ENDPOINT instead of the regular form submits. Here's how it could look like in practice.

<template>
  <div class="app-advanced p-10">
    <img class="mx-auto" alt="Vue logo" src="../assets/logo.png" />

    <form
      :action="FORM_ENDPOINT"
      @submit="handleSubmit"
      method="POST"
      class="w-1/2 mx-auto mt-5"
    >
      <div class="mb-3 pt-0">
        <input
          type="text"
          placeholder="Your name"
          name="name"
          class="
            px-3
            py-3
            placeholder-gray-400
            text-gray-600
            relative
            bg-white bg-white
            rounded
            text-sm
            border-0
            shadow
            outline-none
            focus:outline-none
            focus:ring
            w-full
          "
          required
        />
      </div>

      <div class="mb-3 pt-0">
        <input
          type="email"
          placeholder="Email"
          name="email"
          class="
            px-3
            py-3
            placeholder-gray-400
            text-gray-600
            relative
            bg-white bg-white
            rounded
            text-sm
            border-0
            shadow
            outline-none
            focus:outline-none
            focus:ring
            w-full
          "
          required
        />
      </div>

      <div class="mb-3 pt-0">
        <textarea
          placeholder="Your message"
          name="message"
          class="
            px-3
            py-3
            placeholder-gray-400
            text-gray-600
            relative
            bg-white bg-white
            rounded
            text-sm
            border-0
            shadow
            outline-none
            focus:outline-none
            focus:ring
            w-full
          "
          required
        />
      </div>

      <div class="mb-3 pt-0">
        <button
          class="
            bg-blue-500
            text-white
            active:bg-blue-600
            font-bold
            uppercase
            text-sm
            px-6
            py-3
            rounded
            shadow
            hover:shadow-lg
            outline-none
            focus:outline-none
            mr-1
            mb-1
            ease-linear
            transition-all
            duration-150
          "
          type="submit"
        >
          Send a message
        </button>
      </div>
    </form>

    <div v-if="status" class="text-center mt-10">
      <h2 class="text-2xl">Thanks you!</h2>
      <div class="text-md">{{ status }}</div>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
export default {
  setup() {
    const FORM_ENDPOINT = ref(endpointUrl);
    const status = ref();

    function handleSubmit(e) {
      e.preventDefault();

      // Anything you need to inject dynamically
      const injectedData = {
        DYNAMIC_DATA_EXAMPLE: 123,
      };

      const inputs = e.target.elements;
      const data = {};

      inputs.forEach((inp) => {
        if (inp.name) {
          data[inp.name] = inp.value;
        }
      });

      Object.assign(data, injectedData);

      fetch(FORM_ENDPOINT.value, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => {
          // It's likely a spam/bot request, so bypass it to validate via captcha
          if (response.status === 422) {
            Object.keys(injectedData).forEach((key) => {
              const el = document.createElement("input");
              el.type = "hidden";
              el.name = key;
              el.value = injectedData[key];

              e.target.appendChild(el);
            });

            e.target.submit();
            throw new Error("Please finish the captcha challenge");
          }

          if (response.status !== 200) {
            throw new Error(response.statusText);
          }

          return response.json();
        })
        .then(() => (status.value = "We'll be in touch soon."))
        .catch((err) => (status.value = err.toString()));
    }

    return { status, handleSubmit, FORM_ENDPOINT };
  },

  // To Add Tailwind
  beforeCreate() {
    if (document) {
      const stylesheet = document.createElement("link");
      stylesheet.rel = "stylesheet";
      stylesheet.href =
        "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css";

      document.head.appendChild(stylesheet);
    }
  },
};
</script>

The core idea is that you send a POST request to the FORM_ENDPOINT of your contact form. But it doesn't matter which way you do it. It can be a regular form submit with ajax handler upon form submission or a completely different request that doesn't involve HTML forms at all

Treat it as a REST API because as long as you're sending POST, you'll be good to go. Your vue form submission will reach your inbox.