By Michael Thiessen

Click “like” to see, wechat search ** [big move the world],B station pay attention to [front-end small wisdom] ** this does not have a big factory background, but has a positive attitude. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

The Vue V-Model is a directive that provides two-way data binding between input and form or between two components.

This is a simple concept in Vue development, but the true power of the V-Model takes some time to understand.

This article focuses on the different use cases for v-Model and learning how to use it in your own projects.

What is a V-Model?

As mentioned, v-model is an instruction that we can use in template code. The directive is a template token that tells Vue how we want to handle the DOM.

In the case of the V-Model, it tells Vue that we want to create a two-way data binding between the value in the template and the value in the data property.

A common use case for using v-Models is when designing elements related to forms. We can use it to enable the input element to modify the data in the Vue instance.

<template>
  <div>
    <input 
      type='text'
      v-model='value'
    />
    <p> Value: {{ value }} </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 'Hello World'  
    }
  }
}
</script>
Copy the code

As we enter content in the input, we see that our data attributes are changing

What’s the difference between V-model and V-bind?

The V-bind directive usually switches with the V-model. The difference between the two is that the V-Model provides two-way data binding.

In our case, this means that if our data changes, our input will change, and if our input changes, our data will change.

V-bind binds data in only one way.

This is useful when we want to create a clear one-way flow of data in our own applications. However, you must be careful when choosing between v-model and V-bind.

Modifier for v-model

Vue provides two modifiers that allow us to change the functionality of the V-Model. Each of these can be added up like this, or even joined together.

<input 
  type='text'
  v-model.trim.lazy='value'
/>
Copy the code

.lazy

By default, the V-Model synchronizes with the state (data attributes) of the Vue instance on each input event. This includes gaining/losing focus, etc.

The lazy modifier modifies our V-model so it only synchronizes after changing events. This reduces the number of times the V-Model tries to synchronize with Vue instances and, in some cases, improves performance.

.number

Normally, input automatically changes the input value to a string, even if it is of a numeric type. One way to ensure that our value is treated as a number is to use the.number modifier.

According to the Vue documentation, if the input changes and parseFloat() cannot resolve the new value, the last valid value of the input is returned.

<input 
  type='number'
  v-model.number='value'
/>
Copy the code

.trim

Similar to the trim method in most programming languages, the.trim modifier removes leading or trailing whitespace before returning a value.

Use v-Models in custom components

In Vue, data binding has two main steps:

  1. Pass data from the parent node
  2. Issues events from child instances to update the parent instance

Using v-Models on custom components allows us to pass a prop that handles an event with an instruction.

<custom-text-input v-model="value" /> <! -- IS THE SAME AS --> <custom-text-input :modelValue="value" @update:modelValue="value = $event" />Copy the code

What the hell does that even mean?

The default name for the value passed using v-model is modelValue. However, we can also pass a custom name like this.

<custom-text-input v-model:name="value" />
Copy the code

Note: When we use custom model names, the name of the emitted method will be Update :name.

Use v-Models in custom components

To use V-mode in custom components, you need to do two things:

  1. Receive in propsv-modelThe value of the.
  2. Emits an update event when the corresponding value changes

Ok, first to declare:

export default {
  props: {
    modelValue: String,
  }
}
Copy the code

Next, we bind modelValue to the desired element, and when the value changes, we issue the new value via Update :modelValue.

This allows for bidirectional binding.

Tips for using the V-Model

Now that you’ve seen how to use v-Model in a custom component, let’s look at some of the more advanced uses of v-Model directives.

Use the V-Model multiple times for a component

V-models are not limited to one per component. To use the V-Model multiple times, we just need to make sure we name it uniquely and access it correctly in the child component.

Add a second V-Model for the following component, named lastName first:

<template>
  <div>
    <custom-text-input 
      v-model='value' 
      v-model:lastName='lastName'
    />
    <p> Value: {{ value }} </p>
    <p> Last Name: {{ lastName }} </p>
  </div>
</template>

<script>
import CustomTextInput from './CustomTextInput.vue'

export default {
  components: {
    CustomTextInput,
  },
  data() {
    return {
      value: 'Matt',
      lastName: 'Maribojoc'
    }
  }
}
</script>
Copy the code

Then, our internal child component:

<template>
  <div>
    <label> First Name </label>
    <input 
      type='text'
      :value='modelValue'
      placeholder='Input'
      @input='$emit("update:modelValue", $event.target.value)'
    />
    <label> Last Name </label>
    <input 
      type='text'
      :value='lastName'
      placeholder='Input'
      @input='$emit("update:lastName", $event.target.value)'
    />
  </div>
</template>

<script>
export default {
  props: {
    lastName: String,
    modelValue: String,
  }
}
</script>
Copy the code

After running, you can see that both V-Models work properly:

Customize v-Model modifiers

There are some built-in modifiers in Vue, but these are not enough, so sometimes you need to customize your own modifiers.

Suppose we want to create a modifier that removes all whitespace from the input text. We call it no-whitespace:

<custom-text-input 
  v-model.no-whitespace='value' 
  v-model:lastName='lastName'
/>
Copy the code

Within the component, we can use props to capture modifiers. The name for custom modifiers is nameModifiers

props: {
  lastName: String,
  modelValue: String,
  modelModifiers: {
    default: () => ({})
  }
},
Copy the code

The first thing we need to do is change the @Input handler to use a custom method. We can call it emitValue, which accepts the name of the property and event object being edited.

<label> First Name </label>
<input 
      type='text'
      :value='modelValue'
      placeholder='Input'
      @input='emitValue("modelValue", $event)'
/>
Copy the code

In the emitValue method, we check the modifier before calling $emit. If the no-whitespace modifier is true, it can be modified before it is sent to the parent object.

emitValue(propName, evt) {
  let val = evt.target.value
  if (this.modelModifiers['no-whitespace']) {
    val = val.replace(/\s/g, '')
  }
  this.$emit(`update:${propName}`, val)
}
Copy the code

2. To run or run perfectly:

conclusion

Hopefully, this article will teach you some new knowledge about the Vue V-Model.

In its basic use cases, such as forms and input data, the V-Model is a very simple concept. However, when we create custom components and process more complex data, we can unlock the true power of the V-Model.

~ finish, I am brush bowl wisdom, I am going to brush bowl, we will see you next time!


The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: learnvue co / 2021/01 / eve…

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.