Vue.js form processing technical guide

foreword

insert image description here
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :

Java one-stop service
Front-end cool code sharing
uniapp-from construction to promotion
From 0 to hero, Vue's road to god
Solving algorithm, one column is enough
Let's talk about architecture from 0
The subtle way of data circulation

Please add a picture description


insert image description here

1 Introduction to Vue.js form processing

1.1 What is Vue.js form processing

In web development, forms are an important part of how users interact with applications. Vue.js is a popular JavaScript framework that provides powerful tools and mechanisms for working with form data. Vue.js form handling enables developers to easily collect, validate and submit user-entered data.

The core concept of Vue.js form handling is two-way data binding. By binding form elements to data attributes in the Vue instance, any changes to the form elements will automatically update the data in the Vue instance, and vice versa. This two-way binding makes form handling very clean and efficient.

1.2 Vue.js two-way binding principle

The two-way binding of Vue.js is achieved by using directives (Directives) and the reactive system. Directives are special HTML attributes that tell Vue.js how to handle DOM elements. In form processing, the most commonly used directive is v-model.

v-modelDirectives allow two-way binding of form elements to data properties in a Vue instance. When the user enters content in the form element, v-modelthe data in the Vue instance is automatically updated. Conversely, if the data in the Vue instance changes, the form elements bound to that data will be updated accordingly.

Here is a simple example showing how to use v-modeldirectives to achieve two-way binding:

<div id="app">
  <input type="text" v-model="message">
  <p>{
   
   { message }}</p>
</div>

<script>
  var app = new Vue({
      
      
    el: '#app',
    data: {
      
      
      message: ''
    }
  });
</script>

In the example above, the element is two-way bound <input>via a property v-model="message"on the Vue instance . messageAs the user types in the input box, messagethe properties are automatically updated. At the same time, <p>the text in the element will be updated to show the latest messagevalue.

In this way, Vue.js makes form handling very simple and intuitive. Developers don't need to manually monitor the events of form elements or write a lot of DOM operation codes, they only need to focus on data processing and business logic.

2. Two-way binding and form input

2.1 Use v-model to realize two-way binding

In Vue.js, v-modeldirectives can be used to implement two-way binding, which associates the value of a form element with the data attribute of a Vue instance. In this way, when the value of the form element changes, the corresponding data attribute will also be updated; conversely, when the value of the data attribute changes, the value of the form element will also be updated.

Here is a simple example showing how to implement v-modeltwo-way binding using:

<template>
  <div>
    <input type="text" v-model="message">
    <p>{
   
   { message }}</p>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      message:    };
  }
};
</script>

In the above example, we created a text input box and a paragraph tag. v-modelBind the value of the text input box with the data attribute two-way through the instruction message. As the user types in the text input box, messagethe value of is automatically updated and displayed in the paragraph tag.

2.2 Handling different types of form input

Vue.js provides a variety of directives and techniques to handle different types of form input. Here are some common form input types and how they are handled accordingly:

text input

For text input fields, v-modeltwo-way binding can be achieved using directives, as shown in the previous examples.

<input type="text" v-model="message">

multiline text input

For multi-line text input boxes, v-modeldirectives can be used and textareathe element can be used as a form element.

<textarea v-model="message"></textarea>

check box

For checkboxes, you can use v-modeldirectives and bind data attributes to checkboxthe elements. When the checkbox is checked or unchecked, the value of the data attribute is updated accordingly.

<input type="checkbox" v-model="isChecked">

single button

For radio buttons, you can use v-modeldirectives and bind data properties to each radio button. When a different radio button is selected, the value of the data attribute is updated with the corresponding value.

<input type="radio" value="option1" v-model="selectedOption">
<input type="radio" value="option2" v-model="selectedOption">
``### 下拉列表

对于下拉列表,可以使用`v-model`指令,并将数据属性绑定到`select`元素上。当选择不同的选项时,数据属性的值会更新为选中选项的值。

```html
<select v-model="selectedOption  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

By using appropriate directives and binding methods, you can easily handle different types of form input and implement two-way binding. In this way, you can easily manage and manipulate form data in your Vue.js application.

3 Form Validation

Form validation is a very important technology in front-end development. It is used to ensure that the data entered by the user conforms to the expected format and rules. In this section, we will discuss the importance of form validation, the choice of Vue.js form validation plugins, and common form validation techniques.

3.1 The importance of form validation

The importance of form validation is self-evident. By validating user input, we can prevent invalid or malicious data from being submitted to the backend server, improving system security. At the same time, form verification can also improve user experience, prompt users for errors in a timely manner and guide the correct input method, reducing user confusion and erroneous operations.

3.2 Selection of Vue.js form validation plugin

Vue.js is a popular JavaScript framework that provides a rich ecosystem and plugins to simplify the implementation of form validation. Here are some commonly used Vue.js form validation plugins:

  • VeeValidate: VeeValidate is a powerful and flexible form validation plugin that supports multiple validation rules, custom error messages, and asynchronous validation.
  • vuelidate: vuelidate is another popular Vue.js form validation plugin that is simple to use and easy to integrate into existing projects. It provides a concise set of validation rules and the option to customize error messages.
  • Element UI: Element UI is a Vue.js based UI component library that provides some built-in form validation functionality. Basic form validation can be easily implemented by using Element UI's form component.

It is very important to choose a plug-in that suits your project needs, and you can choose according to the size, complexity, and personal preference of the project.

3.3 Common Form Validation Techniques

In addition to using the Vue.js form validation plugin, there are some common form validation techniques that can be used in front-end development:

3.3.1 HTML5 form validation

HTML5 introduces some new form input types and attributes that enable basic form validation on the browser side. For example, you can use requiredattributes to mark required fields, use patternattributes to specify regular expressions for format validation, use maxlengthand minlengthattributes to limit input length, and so on.

<input type="text" required pattern="[A-Za-z]+" maxlength="10">

3.3.2 JavaScript Validation

JavaScript is a powerful scripting language that enables more complex form validation by writing custom validation functions. The JavaScript function can be triggered when the form is submitted, the user input can be verified, and the corresponding prompt can be given according to the verification result.

function validateForm() {
    
    
  var name = document.getElementById("name").value;
  if (name === "") {
    
    
    alert("请输入姓名");
    return false;
  }
  // 其他验证逻辑...
  return true;
}

3.3.3 Backend verification

Front-end form validation is just an auxiliary means, and the final data validation should be done on the back-end server. Front-end verification can improve user experience and system security, but it cannot replace back-end verification. The back-end verification can conduct a comprehensive verification of all submitted data to ensure the integrity and correctness of the data. In the back-end verification, you can use the server-side programming language (such as Node.js, Python, Java, etc.) to write the verification logic, and return the corresponding error message according to the verification result.

4 Custom form component development

4.1 Why do you need a custom form component

In Vue.js, forms are one of the common interactive elements in web applications. However, when we need to use similar or the same form multiple times in the application, repeatedly writing the same HTML and logic code becomes tedious and error-prone. At this time, custom form components can help us improve code maintainability and reusability.

The custom form component can encapsulate the structure, style and behavior of the form, making it an independent and reusable component. By customizing form components, we can decouple the logic and state of the form from other components, making the code clearer, more readable, and easy to reuse in different scenarios.

4.2 Basic knowledge of component development in Vue.js

In Vue.js, components are the basic unit of building user interfaces. Components can contain content such as templates, data, methods, and styles, and can be referenced and reused by other components.

Here is an example of a simple Vue.js component:

<template>
  <div>
    <h1>{
   
   { title }}</h1>
    <input v-model="inputValue"="text">
    <button @="submitForm">Submit</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: 'Custom Form Component',
      inputValue: ''
    };
  },
  methods: {
    submitForm() {
      // 处理表单提交逻辑
      console.log('Form submitted');
    }
  }
};
</script>

<style scoped>
h1 {
  color: blue;
}
</>

In the example above, we defined a CustomFormcomponent named . It contains a title, an input box and a submit button. Through v-modelinstructions, we Valuebidirectionally bind the value of the input box to the attribute, so that the value of the input box can respond to the user's input changes. When the submit button is clicked, submitFormthe method is triggered, and we can handle the submit logic of the form in this method.

4.3 Develop reusable custom form components

To develop reusable custom form components, we need to consider the following aspects:

4.3.1 Components accept props

Custom form components usually need to accept some parameters to configure their behavior and styling. We can use the props option of Vue.js to define the properties accepted by the component.

<script>
export default {
  props: {
    label: {
      type: String,
      required: true
    },
    value: {
     : [String, Number],
      default: ''
    }
   // ...
};
</script>

In the above example, we defined two props: labeland ``. labelis a required property of type string used to display the label of the form field. valueIs an optional string or number type attribute, the default value is an empty string.

4.3.2 Content distribution using slots

Custom form components usually need to insert some content at a specific position, such as the label of the form field, error message, etc. To achieve this flexibility, we can use the slots feature of Vue.js.

<template>
  <div>
    <label>{
   
   { label }}</>
   ```vue
    <label>{
   
   { label }}</label>
    <slot></slot>
    <div v-if="error" class="error">{
   
   { error }}</div>
  </div>
</template>

In the above example, we have used a default slot <slot></slot>to insert the content of the component. In this way, when using custom form components, we can insert arbitrary content inside the component label, such as input boxes, check boxes, etc.

4.3.3 Using v-model to realize two-way binding

In order to enable two-way data binding between custom form components and parent components, we can use Vue.js v-modeldirectives.

<template>
  <div>
    <input :value="value" @input="$emit('input', $event.target.value)">
  </div>
</template>

In the above example, we use :valueto bind the value of the input box to the ``property, and @listen to the input event of the input box. When the value of the input box changes, we $emittrigger inputa custom event named by the method and pass the new value as a parameter.

4.3.4 Send custom events

Custom form components usually need to send a custom event when a specific interaction occurs, so that the parent component can listen and handle it accordingly. We can use Vue.js $emitmethods to send custom events.

<template>
  <div>
    <button @click="$emit('submit')">Submit</button>
  </div>
</template>

In the above example, when the submit button is clicked, we $emitfire submitthe custom event called via the method.

4.4 Using custom form components

Using a custom form component is similar to using other Vue.js components. First, we need to introduce the custom form component in the parent component and componentsregister it in the options.

<template>
  <div>
    <custom-form :label="formLabel" v-model="formValue" @submit="handleFormSubmit">
      <input type="text" v-model="formValue">
    </custom-form>
  </div>
</template>

<script>
import CustomForm './CustomForm.vue';

export default {
  components: {
    CustomForm
  },
  data() {
    return {
      formLabel: 'Name',
      form: ''
    };
  },
  methods: {
    handleFormSubmit() {
 // 处理表单提交逻辑
      console.log('Form submitted');
    }
  }
};
</script>

In the above example, we have introduced the custom form component in the parent component CustomFormand passed formLabelthe and formValueas props to it. Inside the custom form component, we use a slot to insert the input box and v-modelimplement two-way data binding with the parent component. The method is triggered when the submit button is clicked handleFormSubmit.

This way, we can use the custom form component in the parent component and configure and handle the logic of the form as needed.

5 Example Application: Login Form Processing

In web development, login forms are a common feature. This example will guide you through the process of building a login form, implementing form validation logic, and submitting form data to interact with the backend.

5.1 Building the login form

First, we need to build a login form with username and password fields. HTML and CSS can be used to create the look and layout of the form. Here is a simple example:

<form id="login-form  <div>
    <label for="username">用户名:</label>
    <input type="text" id="username"="username" required>
  </div>
  <div>
    <label for="password">密码:</label>
    <input type="password" id="password" name="password" required>
  </div>
  <button type="submit">登录</button>
</form>
``在上面的代码中,我们使用`<form>`元素创建了一个表单,并为每个输入字段添加了相应的`<input>`元素。`required`属性指定这些字段为必填项。

## 5.2 实现表单验证逻辑

接下来,我们需要实现表单验证逻辑,以确保用户输入的数据符合要求。通常,我们会使用JavaScript来进行表单验证。以下是一个简单的示例:

```javascript
document.getElementById('login-form').addEventListener('submit', function(event) {
  event.preventDefault(); // 阻止表单默认提交行为

  var username = document.getElementById('username').value;
  var password = document.getElementById('password').value;

  if (username === '' || password === '') {
    alert('请填写用户名和密码');
    return;
  }

  // 执行其他验证逻辑,例如检查用户名和密码的格式是否正确

  // 如果通过验证,可以继续提交表单数据与后端交互
});

In the above code, we use the method to add a listener addEventListenerto the event of the form . submitThis listener will fire when the user clicks the login button.

In the listener function, we first call event.preventDefault()the method to prevent the form's default submit behavior. Then, we get the values ​​of the username and password fields and do a simple validation to make sure they are not empty.

You can add other verification logic according to actual needs, such as checking whether the username and password are in the correct format.

5.3 Submit form data and interact with the backend

Finally, we need to submit the form data to the backend server for processing. Usually, we will use AJAX or form submission to achieve this process. Here's an example using AJAX:

document.getElementById('login-form').addEventListener('submit', function(event) {
    
    
  event.preventDefault(); // 阻止表单默认提交行为

  var username = document.getElementById('username').value;
  var password = document.getElementById('password').value;

  if (username === '' || password === '') {
    
    
    alert('请填写用户名和密码    return;
  }

  // 执行其他验证逻辑,例如检查用户名和密码的格式是否正确

  // 使用AJAX将表单数据提交给后端
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/login', true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState === 4 && xhr.status === 200) {
    
    
      // 处理登录成功的逻辑
      var response = JSON.parse(xhr.responseText);
      alert('登录成功!欢迎,' + response.username + '!');
    } else if (xhr.readyState === 4 && xhr.status !== 200
) {
    
    
      // 处理登录失败的逻辑
      alert('登录失败,请检查用户名和密码是否正确。');
    }
  };
  
  var data = {
    
    
    username: username,
    password: password
  };
  
  xhr.send(JSON.stringify(data));

In the code above, we sent a POST request to /loginthe endpoint using AJAX and sent the form data as a JSON string. We set the request header Contentto application/jsonto specify the format of the request body.

In xhr.onreadystatechangethe callback function, we process according to the status code of the response. If the status code is 200, it means that the login is successful, and we can execute the corresponding logic. If the status code is not 200, it means that the login failed, and we can display the corresponding error message to the user.

Guess you like

Origin blog.csdn.net/Why_does_it_work/article/details/131792256