Complete solution to Vue form processing

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


form processing

In daily development, forms are used everywhere, such as login, problem feedback functions, etc. Data collection and binding of forms are also very routine work. Processing forms in general development requires manipulating the DOM, which is a relatively tedious and inefficient task. However, in a Vue project you can use the v-model directive to create two-way data binding on the form , and elements. Easily implement form data collection or binding, improving development efficiency. It automatically chooses the correct method to update the element based on the control type. Responsible for listening to user input events to update data, and perform some special processing for some extreme scenarios. Next, we will take you through its basic usage.

Knowledge points

  • v-model directive
  • Basic usage
  • value binding
  • modifier

Basic usage

Common form elements
Insert image description here
注意

Note 1: v-model will ignore the initial values ​​of the value, checked, and selected attributes of all form elements and always use the data of the Vue instance as the data source. Assigning a value to an element directly will not work. You should declare the initial value in the data option of the component through JavaScript.

Note 2: v-model internally uses different attributes for different input elements and throws different events. This is specifically reflected in the form modifiers section and will be explained to you:

  • text and textarea elements use value attributes and input events (internally listen to input events);
  • checkbox and radio use the checked attribute and change event (listening to the change event internally);
  • The select field takes value as a prop and change as an event (listening to the change event internally).

Note: The difference between change and input is that input updates data in real time, while change does not update data in real time.

input monitoring
change monitoring

With precautions in mind, enter Vue form processing to learn.

text

Directly bind the v-model directive to the text and declare the bound data item in the data data item to easily complete two-way data binding. Let's take a look at the magic v-model directive.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>syl-vue-test</title>
    <!-- 引入 vue.js -->
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <input v-model="msg" placeholder="请输入..." />
      <p>输入的是: {
   
   { msg }}</p>
    </div>
    <script>
      var app = new Vue({
      
      
        el: "#app",
        data: {
      
      
          msg: "",
        },
      });
    </script>
  </body>
</html>

multiline text

The usage of multi-line text and text is the same. Use the v-model directive and declare the bound message data item in the instance data to complete the two-way binding of multi-line text data.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <span>Multiline message is:</span>
      <p style="white-space: pre-line;">{
   
   { message }}</p>
      <br />
      <textarea v-model="message" placeholder="add multiple lines"></textarea>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            message: "",
          };
        },
      });
    </script>
  </body>
</html>

Insert image description here

single button

Binding the radio buttons to the same picked can complete the data binding. When the first radio button is selected, the value of picked is the value of the first radio button. Similarly, when the second radio button is selected, the value of picked is The value is the value of the second radio button.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 将单选按钮绑定到同一个 picked -->
      <input type="radio" id="one" value="One" v-model="picked" />
      <label for="one">One</label>
      <br />
      <input type="radio" id="two" value="Two" v-model="picked" />
      <label for="two">Two</label>
      <br />
      <span>Picked: {
   
   { picked }}</span>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            picked: "",
          };
        },
      });
    </script>
  </body>
</html>

Insert image description here

checkbox

The check box is bound to a Boolean value (true or false). Also use the v-model directive on the check box element and declare checked in the instance data to complete the two-way binding of the check box data.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <input type="checkbox" id="checkbox" v-model="checked" />
      <label for="checkbox">{
   
   { checked }}</label>
    </div>
    <script>
      // 绑定布尔值
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            checked: false,
          };
        },
      });
    </script>
  </body>
</html>

multiple checkboxes

Usually in development, multiple check boxes are used, so we need to bind the check boxes to the same array to facilitate data collection.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <input type="checkbox" id="syl1" value="syl1" v-model="checkedNames" />
      <label for="syl1">syl1</label>
      <input type="checkbox" id="syl2" value="syl2" v-model="checkedNames" />
      <label for="syl2">syl2</label>
      <input type="checkbox" id="syl3" value="syl3" v-model="checkedNames" />
      <label for="syl3">syl3</label>
      <br />
      <span>Checked names: {
   
   { checkedNames }}</span>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            checkedNames: [],
          };
        },
      });
    </script>
  </body>
</html>

selection box

Use the v-model directive on the select element to bind the currently selected option.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- select 标签是绑定  数据项 selected -->
      <select v-model="selected">
        <option disabled value="">请选择</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
      </select>
      <span>Selected: {
   
   { selected }}</span>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            selected: "",
          };
        },
      });
    </script>
  </body>
</html>

Insert image description here

value binding

Text and multiline text value binding

Specifying value directly on the label will not succeed and will be ignored by Vue.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>syl-vue-test</title>
    <!-- 引入 vue.js -->
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 直接给 value 不会生效 -->
      <input v-model="msg" value="hello" />
    </div>
    <script>
      var app = new Vue({
      
      
        el: "#app",
        data: {
      
      
          msg: "",
        },
      });
    </script>
  </body>
</html>

Insert image description here

Correct mode, declare the initial value via JavaScript in the component's data option:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>syl-vue-test</title>
    <!-- 引入 vue.js -->
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 直接给 value 不会生效 -->
      <input v-model="msg" />
      <br />
      <br />
      <br />
      <textarea v-model="msg"></textarea>
    </div>
    <script>
      var app = new Vue({
      
      
        el: "#app",
        data: {
      
      
          msg: "hello",
        },
      });
    </script>
  </body>
</html>

Insert image description here

single button

checkbox and radio use the checked attribute, so the element value is given directly. When selected, the value of the binding item declared in data is the element value.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 当选中时,`picked` 为字符串 "a" -->
      <input type="radio" v-model="picked" value="a" />
      {
   
   {picked}}
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            picked: "",
          };
        },
      });
    </script>
  </body>
</html>

Insert image description here

checkbox

A checkbox can be a Boolean value, with a toggle of true or false when selected and false when unselected.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 当复选框选中时,toggle 的值为 true,未选中为 false -->
      <input type="checkbox" v-model="toggle" />
      {
   
   {toggle}}
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            toggle: false,
          };
        },
      });
    </script>
  </body>
</html>

In daily development, the value of the check box is often a specific value, so we can do this and declare the two attributes true-value="yes" and false-value="no" in the label. When selected, It is the value specified by the true-value attribute. When it is not selected, it is the value of the false-value attribute.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>

  <body>
    <div id="app">
      <input
        type="checkbox"
        v-model="toggle"
        true-value="yes"
        false-value="no"
      />
      <p>toggle:{
   
   {toggle}}</p>
    </div>
    <script>
      // 通过 true-value="yes" false-value="no" 属性控制,选中时 toggle 值为 yes,未选中时为 no
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            toggle: "",
          };
        },
      });
    </script>
  </body>
</html>

If you only want to select items with a value, you can do this by specifying the value for the true-value attribute and setting the false-value attribute to a null value.

<input type="checkbox" v-model="toggle" true-value="name" false-value="" />

selection box

The value binding of the selection box directly specifies the value of each option, which can be fixed or dynamically bound using v-bind:value:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 当选中第一个选项时,selected 为字符串 "abc" -->
      <select v-model="selected">
        <!-- 固定赋值value -->
        <option value="abc">ABC</option>
        <!-- 使用 v-bind 绑定值 -->
        <option v-bind:value="optionValue">DEF</option>
      </select>
      <p>{
   
   {selected}}</p>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            selected: "",
            // 第二个 option 的值
            optionValue: "efg",
          };
        },
      });
    </script>
  </body>
</html>

Insert image description here

modifier

Vue summarizes the form processing business that is often performed in daily development, encapsulates it, and uses form modifiers to easily solve some form processing business logic.

.lazy

When we started to introduce form processing, we mentioned a few things to note. Different elements use different values ​​and throw different events. Maybe during development, we don't need the data to be updated in real time. So, how do we replace the input event with the change event? We can use the .lazy modifier to change the thrown event from input to change, so that the form elements are updated lazily and not in real time. .

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>

  <body>
    <div id="app">
      <!--使用 .lazy 修饰符将文本框 抛出的事件改为 change 事件,不再实时更新,只有文本框失去焦点才更新数据 惰性更新 -->
      <input v-model.lazy="msg" />
      <p>{
   
   {msg}}</p>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data: {
      
      
          msg: "hello",
        },
      });
    </script>
  </body>
</html>

Insert image description here

.number

If you want to automatically convert user input values ​​to numeric types, you can add the number modifier to v-model:

This is often useful because even when type="number" the value of an HTML input element returns a string (the default), requiring your own type conversion. If the value cannot be parsed by parseFloat(), the original value is returned. Add the number modifier to v-model. Even if the user inputs a non-numeric type, it will be converted. If the conversion cannot be performed, the original value will be returned.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>

  <body>
    <div id="app">
      <p>没有使用 .number 修饰符</p>
      <input v-model="number1" type="number" />
      <!-- 使用 typeof 对值类型检测 -->
      <p>{
   
   {typeof(number1)}}</p>
      <p>使用 .number 修饰符</p>
      <input v-model.number="number2" type="number" />
      <!-- 使用 typeof 对值类型检测 -->
      <p>{
   
   {typeof(number2)}}</p>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data: {
      
      
          number1: "",
          number2: "",
        },
      });
    </script>
  </body>
</html>

Insert image description here

.trim

Form element values ​​are automatically filtered by spaces at the beginning and end.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
  </head>

  <body>
    <div id="app">
      <input v-model.trim="msg" type="text" />
      <p>首尾空格被过滤了:{
   
   {msg}}</p>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data: {
      
      
          msg: "",
        },
      });
    </script>
  </body>
</html>

Insert image description here

Comprehensive exercises

Form data collection and binding.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>vue</title>
    <script src="vue.min.js"></script>
    <style>
      * {
      
      
        padding: 0;
        margin: 0;
      }
      html,
      body {
      
      
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      #app {
      
      
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        width: 400px;
        height: 400px;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <form class="app-form">
        <span>name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <input type="text" v-model="username" />
        <br />
        <span>password:</span><input type="password" v-model="password" />
        <br />
        <span
          >sex:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
        >
        <input type="radio" id="man" value="man" v-model="sex" />
        <label for="man">man</label>
        <input type="radio" id="woman" value="woman" v-model="sex" />
        <label for="woman">women</label>
        <br />
        <span>hobby:</span>
        <input type="checkbox" id="game" value="game" v-model="hobby" />
        <label for="game">game</label>
        <input
          type="checkbox"
          id="basketball"
          value="basketball"
          v-model="hobby"
        />
        <label for="basketball">basketball</label>
        <input type="checkbox" id="study" value="study" v-model="hobby" />
        <label for="study">study</label>
        <br />
        <br />
        <p>名字:{
   
   {username}}</p>
        <p>密码:{
   
   {password}}</p>
        <p>性别:{
   
   {sex}}</p>
        <p>爱好:{
   
   {hobby}}</p>
      </form>
    </div>
    <script>
      var vue = new Vue({
      
      
        el: "#app",
        data() {
      
      
          return {
      
      
            username: "",
            password: "",
            sex: "man", // 性别单选默认勾选男
            hobby: [],
          };
        },
      });
    </script>
  </body>
</html>

Insert image description here

Guess you like

Origin blog.csdn.net/Argonaut_/article/details/129256287