0

First of all, please be kind. I'm new to VueJS coming from the Angular world where things are different ;-)

I am creating a multi-page website using VueJS for simple things like a floaty header and submission of forms etc. I'd like the markup for my contact form to be in my HTML (rendered by the CMS) and I'd like to have VueJS handle the form submission and replacing the form with a thank-you message. So, a simplified version of the form would look like this.

<contact-form>

    <form class="contact-form_form">

        ...
        <input name="emailaddress" type="text" />
        ...

        <button></button>

    </form>

    <div class="contact-form_thanks">
        Thanks for filling in this lovely form
    </div>

</contact-form>

So, the obvious thing to do is to create a VueJS component, but I don't want it to introduce a new template, I just want it to submit the form when the button is pressed (using Axios) and hide the form and show the thank you message.

I know how to do all of this in angular using attribute directives and ng-show/hide etc. but can't really see how to do this in VueJS because all the tutorials are geared to wards SPAs and Single file components with templates.

Any kick in the right direction would be appreciated.

1 Answer 1

1

Seems like you just want a data item indicating whether the form has been submitted, and v-if and v-else to control what displays in either case.

new Vue({
  el: 'contact-form',
  components: {
    contactForm: {
      data() {
        return { hasBeenSubmitted: false };
      },
      methods: {
        doSubmit() {
          console.log("Some behind-the-scenes submission action...");
          this.hasBeenSubmitted = true;
        }
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<contact-form inline-template>

  <div v-if="hasBeenSubmitted" class="contact-form_thanks">
    Thanks for filling in this lovely form
  </div>

  <form v-else class="contact-form_form">

    ...
    <input name="emailaddress" type="text" /> ...

    <button @click.prevent="doSubmit">Submit</button>

  </form>


</contact-form>

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Roy, thanks for the answer. This would work but I'd like it to be reusable, hence I wanted to create a component so that wherever a contact form was used on the site it would work without having to have these methods and data on the main Vue instance.
Ta-da! It's a component. Do you want the form contents to be a slot?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.