Home  >  Article  >  Web Front-end  >  How to implement form verification and submission in Vue

How to implement form verification and submission in Vue

王林
王林Original
2023-10-15 11:14:051282browse

How to implement form verification and submission in Vue

How to implement form verification and submission in Vue

In web development, the form is an important interface for users to interact with the web page. The data entered by the user in the form Verification and submission are required to ensure the legality and integrity of the data. Vue.js is a popular front-end framework that provides convenient form verification and submission methods, allowing us to quickly implement form functions. This article will introduce how to use Vue.js to implement form verification and submission, and provide specific code examples.

1. Form validation

  1. Installationvee-validatePlug-in

Vue.js provides a powerful form validation Validation plug-in vee-validate, first we need to install the plug-in through npm.

npm install vee-validate
  1. Introduce the plug-in into main.js

Introduce the plug-in into the main.js file of the project and register it.

import Vue from 'vue';
import VeeValidate from 'vee-validate'; // 引入vee-validate插件

Vue.use(VeeValidate); // 注册插件
  1. Add validation rules to the form
<template>
  <form @submit.prevent="submitForm">
    <div class="form-group">
      <label for="name">姓名</label>
      <input type="text" v-model="name" v-validate="'required'" name="name">
      <span v-show="errors.has('name')">{{ errors.first('name') }}</span>
    </div>
    <div class="form-group">
      <label for="email">邮箱</label>
      <input type="email" v-model="email" v-validate="'required|email'" name="email">
      <span v-show="errors.has('email')">{{ errors.first('email') }}</span>
    </div>
    <button type="submit">提交</button>
  </form>
</template>

In the above sample code, we added v-validate# to the two input boxes respectively. ##instruction. The v-validate command is used to specify verification rules and split multiple verification rules with |. Here, we set the name to required, which cannot be empty; set the email address to required and email, which cannot be empty and must be in email format . Use errors.has('name') and errors.first('name') to detect and display verification error information.

    Verify the form and submit
  1. <script>
    export default {
      data() {
        return {
          name: '',
          email: ''
        };
      },
      methods: {
        submitForm() {
          this.$validator.validateAll().then(result => {
            if (result) {
              // 表单校验通过,提交表单
              // 这里可以调用API进行数据提交
              console.log('表单提交成功');
            }
          });
        }
      }
    };
    </script>
In the above code, we defined a

submitForm in methods Method, which is triggered when the user clicks the submit button. In the submitForm method, verify the entire form through this.$validator.validateAll() and return a Promise object. If the verification passes, Promise will return true, and we can submit the form in the callback function.

2. Form submission

After the form verification passes, we can submit the form. Here we use the

axios library to send HTTP requests. First, we need to install axios via npm.

npm install axios

Then introduce axios in the Vue component and modify the submitForm method:

import axios from 'axios';

// ...

methods: {
  submitForm() {
    this.$validator.validateAll().then(result => {
      if (result) {
        // 表单校验通过,提交表单
        axios.post('/api/submit', {
          name: this.name,
          email: this.email
        }).then(response => {
          console.log('表单提交成功');
        }).catch(error => {
          console.error('表单提交失败', error);
        });
      }
    });
  }
}

In the above code, we use axios to send a POST request to

/api/submit interface and submit the form data as the request body. Output 'Form submission successful' in the success callback function, and output error information in the failure callback function.

3. Summary

Through the above steps, we used Vue.js and VeeValidate plug-in to implement the form verification and submission function. We only need to simply configure the validation rules and submission interface to easily complete the entire form process. Vue.js provides rich form processing functions, which brings great convenience to our web development.

Of course, the above code is just a basic example. In actual development, there may be more complex verification and submission logic, but the principles are the same. By rationally using the form function of Vue.js, we can help us improve development efficiency and ensure the legality and integrity of data, providing users with a better interactive experience.

The above is the detailed content of How to implement form verification and submission in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn