📜  vue v-model - Html (1)

📅  最后修改于: 2023-12-03 14:48:22.947000             🧑  作者: Mango

Vue v-model - Html

v-model is a directive provided by Vue.js that allows two-way data binding between form inputs and JavaScript data models. It simplifies the process of handling user input and updating the underlying data.

Syntax

The basic syntax for v-model in Vue is:

<input v-model="<dataProperty>">

Here, <dataProperty> refers to a property within the Vue instance data object. The v-model directive will automatically update the data property when the user enters input in the associated input field, and vice versa.

Example

Let's consider an example where we have a Vue component that contains a text input field and a paragraph element. We want to bind the input value to a data property called message and display it in the paragraph element.

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

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

In this example, the v-model directive is used to bind the value of the input field to the message data property. Any changes made in the input field will automatically update the message property, and the updated value will be displayed in the paragraph element.

Modifiers

v-model directive also supports various modifiers to customize its behavior. Some commonly used modifiers are:

  • .lazy: Updates the value only when the input field loses focus.
  • .number: Automatically converts user input to a number type.
  • .trim: Removes leading and trailing whitespace from the input value.

Example usage of modifiers:

<input v-model.lazy="message" placeholder="Enter some text">
<input v-model.number="quantity" type="number">
<input v-model.trim="username" placeholder="Enter your username">
Conclusion

The v-model directive in Vue.js provides a convenient way to handle user input and keep the data in sync. It simplifies the code by eliminating the need to manually update data properties when the input values change. By using modifiers, we can further customize the behavior of v-model to suit different requirements.

For more details, refer to the official documentation.