v-modelis for two way data binding on form, input, textarea, and select.- It is primarily for updating data when users' enter information.
v-modelignores initial attributes on form elements. Instead, it looks for initial attributes indata().
- v-model syntax is used like this:
<input type="text" v-model="userInput">
- In this example, the input is bound to a string called
userInputindata() - It's long form code would look like this:
<input type="text"
v-bind:value="userInput"
v-on:input="userInput = $event.target.value"
>
- The input is set to listen to the
valueof the text input event- See the default properties below
- You will use these property types to achieve proper 2 way binding with
v-model
text&textarea- property: value
- event: input
checkbox&radio- property: checked
- event: change
select- property: value
- event: change
- When the input is placed into a component, the implicit
v-onchanges- Instead of what is depicted above, it looks like:
<input type="text" v-bind:value="userInput" v-on:input="userInput = $event" >- This behaviour will not emit the input content.
- Inside your component change the
v-on:inputto
@input="$emit('input', $event.target.value)"- This will make it emit the content back to the parent
- You can also use
valueinstead of props.
v-bind:value="value- This will bind the value of the output to the value of the parent input.
- Then when using the input content from your input component, make sure to use the same variable from your parent's
data()that is used in thev-model
See this gist for a full example
You can use v-model and v-bind to create an input component that will receive all of it's information from the parent component.
- Remember that
v-modelis specifically targetting thevalueattribute of the input field. This means that it won't access other data - So when passing it an object, make sure the
v-modelis targetting a string, and then usev-bindfor the rest of the information
- Child Template:
<label :for="info.inputName">
{{ info.labelText }}
<input
type="text"
:value="propValue"
@input="$emit('input', $event.target.value)"
:name="info.inputName>
</label>
- Child Script:
props: ["info", "propValue"]
- Parent Template:
<div>
<Child v-model="parentInfo.value" :info="parentInfo" />
</div>
<div>
<p>{{ parentInfo.value }}</p>
</div>
- Parent Script
data() {
return {
parentInfo: {
value: "",
inputName: "input-name",
inputLabel: "Input Label"
}
}
}