Form-related knowledge in Vue3: form binding, form validation, form processing

Form is an interaction method often used in front-end development, which provides a mechanism for users to enter and submit data. As a popular JavaScript framework, Vue3 provides rich form processing functions, allowing us to easily create, validate and obtain form data. This article will introduce the knowledge related to forms in Vue3 in detail, including form binding, form validation, form processing and so on.

form binding

In Vue3, we can use v-modeldirectives to achieve two-way binding between forms and data. v-modelThe instruction will automatically monitor the input event and change event of the form element, and synchronize the value entered by the user to the data, and at the same time reflect the change of the data to the form element. Here is an example:

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

<script>
export default {
  setup() {
    const message = ref('')

    return {
      message
    }
  }
}
</script>

In the above code, we have bidirectionally bound v-modelthe input box and data through instructions . messageWhen the user types in the input box, messagethe value of is automatically updated and displayed on the page. Conversely, if the value of the input box is modified message, the content of the input box will be updated accordingly.

In addition to text input boxes, Vue3 also supports binding other types of form elements, such as check boxes, radio boxes, drop-down boxes, etc. v-modelWe only need to bind the data and form elements with instructions.

form validation

Form validation is an important task to ensure the correctness and completeness of user input data. Vue3 provides rich form validation functions, allowing us to easily verify the data entered by users. Here are some commonly used form validation techniques:

Required field validation

In some cases, we want the user to have to fill in certain fields. In Vue3, you can implement required field validation by setting HTML5 requiredattributes or using custom validation rules. Here is an example:

<template>
  <div>
    <input v-model="name" type="text" required>
    <p v-if="!name">Please enter your name</p>
  </div>
</template>

<script>
export default {
  setup() {
    const name = ref('')

    return {
      name
    }
  }
}
</script>

In the above code, we requiredimplement required field validation by adding attributes to the input box. If the user does not fill in the name, the prompt message "Please enter your name" will be displayed on the page.

format validation

In addition to required field verification, we usually also need to verify the input format, such as email address, mobile phone number, etc. Vue3 can use regular expressions or third-party plug-ins to implement format validation. Here's an example using regular expressions:

<template>
  <div>
    <input v-model="email" type="text">
    <p v-if="!email || !emailRegex.test(email)">Please enter a valid email address</p>
  </div>
</template>

<script>
export default {
  setup() {
    const email = ref('')
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

    return {
      email,
      emailRegex
    }
  }
}
</script>

In the above code, we use regular expressions to validate the format of email addresses. If the email address entered by the user does not meet the rules of the regular expression, the prompt message "Please enter a valid email address" will be displayed on the page.

custom validation

In some cases, we may need to customize form validation according to specific business needs. Vue3 allows us to write custom validation methods and apply them to form elements. Here's an example using a custom validation method:

<template>
  <div>
    <input v-model="password" type="password">
    <p v-if="!validatePassword(password)">Password must contain at least 8 characters</p>
  </div>
</template>

<script>
export default {
  setup() {
    const password = ref('')

    const validatePassword = (value) => {
      return value.length >= 8
    }

    return {
      password,
      validatePassword
    }
  }
}
</script>

In the above code, we define a validatePasswordcustom validation method named , which is used to validate whether the length of the password is greater than or equal to 8 characters. If the password does not meet the verification rules, the prompt message "Password must contain at least 8 characters" will be displayed on the page.

By combining these form validation technologies, we can effectively ensure the correctness of user input data, improve user experience and system stability.

form processing

In addition to form binding and validation functions, Vue3 also provides some auxiliary functions and instructions for form processing, making it easier for us to obtain form data and process form submission events.

get form data

In Vue3, we can use refor reactiveto define form data, and get the data entered by the user by accessing the corresponding reference variable. Here is an example:

<template>
  <div>
    <form @submit="onSubmit">
      <input v-model="name" type="text">
      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script>
export default {
  setup() {
    const name = ref('')

    const onSubmit = (event) => {
      event.preventDefault()
      console.log(`Name: ${name.value}`)
    }

    return {
      name,
      onSubmit
    }
  }
}
</script>

In the above code, we bound v-modelthe input box and data through instructions . nameWhen the user clicks the submit button, onSubmitthe method will be called, and we can name.valueget the name entered by the user.

form reset

In some cases, we need to reset the form to its initial state after the user submits it. Vue3 provides modifiers resetfor methods and v-modeldirectives .lazyto implement form resets. Here is an example:

<template>
  <div>
    <form @submit="onSubmit">
      <input v-model.lazy="name" type="text">
      <button type="submit">Submit</button>
      <button type="button" @click="onReset">Reset</button>
    </form>
  </div>
</template>

<script>
export default {
  setup() {
    const name = ref('')

    const onSubmit = (event) => {
      event.preventDefault()
      console.log(`Name: ${name.value}`)
    }

    const onReset = () => {
      name.value = ''
    }

    return {
      name,
      onSubmit,
      onReset
    }
  }
}
</script>

In the above code, we use .lazymodifiers to delay the update of the form elements until the submit button is clicked to sync the data into namethe variable. nameWe can implement a form reset by setting reset to an empty string when the user clicks the reset button .

Summarize

Vue3 provides powerful and flexible form processing functions, allowing us to easily create, validate and obtain form data. We can v-modelrealize the two-way binding of forms and data through instructions, use various validation techniques to ensure the correctness of user input, and conveniently process form data and events through auxiliary functions and instructions.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131793972