The V-Model is one of the many instructions provided by the Vue framework. Its main function is to create two-way data binding on the ,

What about two-way data binding? Before we get to the V-model directive, let’s talk about two-way data binding.

Two-way data binding

Without further ado, come up directly to show a v-Model example of the code!

// Define the V-Model sample component
Vue.component('bindData', {
  template:` 
      

this is bindData component!

{{inputValue}}

`
, data() { return { inputValue: 'hello'}},methods: {// Click the button to change the input value handleChange() { this.inputValue = `I'm changed`; }}});const app=new Vue({ el: '#app'.template: `
`
}); Copy the code

I believe that the above simple example code is routine for those of you who have been involved in Vue stack project development. If you have not been involved in Vue stack project development or are not familiar with Vue, I would mind you to check the documentation on the official website and try to do a project or two. Then come back to this article and you will learn something new about the V-Model!

The above sample code does a fantastic thing by binding v-Model to the input tag:


v-model

The above detailed list of several operations and the contents of the show, look back at this is two-way data binding! At this point, if you don’t know how the V-Model works, take a moment to think about it or make assumptions about how it works inside the V-Model based on what you already know (💪).

A few minutes passed… [Leering]

V – contact model

Now let’s analyze it:

  • 1. Start with the inputValue attribute, because the only link between the INPUT tag, v-Model tag, Button tag, and P tag is the inputValue attribute.

  • Because the input attribute is defined on $data, that is the response data _ (if you don’t know what the response data is, you can click here), according to the nature of the response data: ** When the data value is modified, it will drive the change of the view and display the changed data. ** Then the content displayed by the corresponding P tag bound to the inputValue attribute will change

  • 3. When we input a value into the input, the content displayed in the P tag also changes accordingly. According to the characteristics of responsive data, this must trigger the change of the inputValue value, and assign the value of the input to the inputValue, resulting in the change of the content of the P tag.

  • 4. When a button is clicked, the input and P tags change and display the same value. In the button binding’s click handler, we assign the new value directly to the inputValue. The P tag shows the value of the inputValue property, so of course it changes. What about input?

  • 5, As far as we know, there is a value attribute on the input, and we can set the display value for the input according to the value attribute. After clicking button, we set inputValue to a new value and input to a different value. There must be an operation to set the value of input’s value property.

  • 6. Points 3 and 5 reveal that there are two implicit operations on input: setting inputValue and setting the value property of input. But there is no binding action shown on the input tag, just a V-Model instruction.

❓ Here we assume that these two implicit operations are wrapped by the V-Model.

Mud-forced transformation of the V-model

Based on the analysis of the above six points, or based on our current knowledge, let’s rewrite the code slightly:

// Define the v-Model sample component rewrite
Vue.component('bindData1', {
  template:` 
      

this is bindData1 component!

Input values are: {{inputValue}}

'
, data() { return { inputValue: 'hello'}},methods: {// Handle the input change event handleInputChange(e) { this.inputValue = e.target.value; }, // Click the button to change the input value handleChange() { this.inputValue = `I'm changed`; }}});const app=new Vue({ el: '#app'.template: `
`
}); Copy the code

The modified code can achieve the same effect of two-way data binding as before, but the modified code has two major changes:

  • 1. Remove the V-model instruction from the input tag, replace it with the V-bind :value instruction to bind the inputValue attribute, and add a V-on :change event;

  • Add an input change handler that assigns the value of the current input tag to the inputValue attribute of $data

Deep v – model

This makes you wonder: it can’t be a coincidence that these two different pieces of code can achieve the same effect of two-way data binding, and there must be some connection between the two approaches.

Yes, the above two examples are basically equivalent implementations. The modified example is a complex implementation before the modified, meaning that the V-Model is just a wrapper or syntactic sugar that listens for user input events to update data and does special processing for extreme scenarios.

The V-Model ignores the initial values of the value, Checked, and Selected features of all form elements and always uses Vue instance data as the data source. You should declare the initial value in the data option of the component via JavaScript.

V-model used on different HTML tags monitors different attributes and throws different events:

  • Text and Textarea elements use value attributes and input events;

  • Checkbox and radio use the Checked attribute and the change event;

  • The SELECT field takes value as prop and change as an event.

See here is not an Epiphany! Here is an example of a select. For more examples, you can visit Vue’s official website:


Custom component V-model

The previous content only explained the use of V-Model in the native form tag, in the usual development of the use of third-party UI library components v-Model is also very good, then custom components v-Model is how to implement?

V-model is implemented by default with a prop named Value and an event named input on custom components, but the value attribute is used for different purposes (as we mentioned above) for different form elements, such as checkboxes and checkboxes represented checked. To distinguish between these different presentation features, Vue provides model configuration properties to components. Model is an object that provides a prop property that specifies the component value feature, and event specifies the event that fires when the value changes.

Said so much, to a sample code!

// Customize the component checkbox
Vue.component('checkbox', {
  template: `  `.model: {
    prop: 'checked'.event: 'change'
  },
  props: {
    checked: Boolean}});// Use custom components
Vue.component('useCheckbox', {
  template: ` 
       `,
  data() {
  	return {
    	checkStatus: false}},methods: {
  	handleChange(checked) {
    	// do something}}});Copy the code

The value of checkStatus in the sample code will be passed to the prop named Checked. The checkStatus property is updated when the checkBox fires a change event with a new value.

⚠️ Note: Note that you still need to declare checked prop in the props option of the component

V – model modifier

We’ve covered the use of v-Model in native form elements and custom components, and we’ve also covered the implementation principles of v-Model. Now you should be familiar with v-Model.

Next, let’s talk about the modifiers used on v-Models.

.lazy

In the above content, we mentioned that V-Model implements two-way data binding. The features of two-way data binding are: When the value displayed on the INPUT label changes in real time, the input event on the input label will be triggered in real time. After the trigger of each input event, the value of the input box will be synchronized with the data in real time. For special requirements and scenarios where you want to synchronize data not in real time but when the change event is triggered, you can add the lazy modifier to handle this, as shown in the following example:

<! Update "change" instead of "input" -->
<input v-model.lazy="msg" >
Copy the code

.number

In forms where input validation must be numeric, such as operations related to money 💰, you may want to automatically convert user input values to numeric types, so you can add the number modifier to the V-Model to handle this.

<! Automatically convert input values to numeric types -->
<input v-model.number="age" type="number">
Copy the code

The ⚠️ number modifier is handled by using the parseFloat() function to process the input value. If the input value is not parsed by parseFloat(), such as a string that begins with a non-number, the original value is returned.

.trim

This trim modifier is useful for strings entered by the user in a form tag where we want to remove whitespace at the beginning and end.

<! -- Remove first and last whitespace characters from input values -->
<input v-model.trim="msg">
Copy the code

conclusion

V-model is a very practical instruction, its use can save us a lot of business logic code, make the code more clear, easier to maintain. Of course, the implementation principle of V-Model is very easy to understand and digest, and in order to make our development more convenient, v-Model provides a very practical modifier to simplify our operation, the use of modifier is also very simple.

V-model implementation principle we are clear, the next section we will say about Vue source code exactly how to achieve v-Model, see you next time 👋!