Categories
Vue Answers

How to reference the form element when we submit a form in Vue.js?

Spread the love

Sometimes, we want to reference the form element when we submit a form in Vue.js.

In this article, we’ll look at how to reference the form element when we submit a form in Vue.js.

How to reference the form element when we submit a form in Vue.js?

To reference the form element when we submit a form in Vue.js, we can use a ref.

For instance, we write

<template>
  <div>
    <form ref="form" @submit.prevent="submit">
      <input v-model="store.vital" />
      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script>
//...
export default {
  //...
  methods: {
    submit() {
      this.$refs.form.$el.submit();
    },
  },
  //...
};
</script>

to add a form and we assign the form ref to it.

And we make the submit method run when we submit the form with @submit.prevent="submit".

The prevent modifier calls event.preventDefault to prevent the default server side submission behavior.

In submit, we get the form element with this.$refs.form.$el.

Conclusion

To reference the form element when we submit a form in Vue.js, we can use a ref.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *