23
Author: Michael Thiessen
Translator: Frontend Xiaozhi
Source: news

There are dreams and dry goods. search 1617f3514b6119 [Great Move to the World] attention to the brushing wisdom who is still doing the dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

image.png

Vue v-model is a command that provides two-way data binding between input and form

This is a simple concept in Vue development, but v-model will take some time to understand.

This article mainly explains v-model and learns how to use it in your own projects.

What is v-model?

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

In v-model , it tells Vue that we want to create a two-way data binding between template and the value in the data

A common use case for using v-model is when designing some elements related to the form. 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>

When we input , we will see that our data attributes are changing

![uploading...]()

image

What is the difference between v-model and v-bind?

v-bind command usually switches v-model The difference between the two is that v-model provides two-way data binding.

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

And v-bind only binds data in one way.

This is very useful when we want to create a clear one-way data flow in our own application. However, you must be careful when v-bind v-model and 0617f3514b66a3.

Modifier of v-model

Vue provides two modifiers that allow us to change the function of v-model Each one can be added up like this, or even connected together.

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

.lazy

By default, v-model synchronized with the state (data attributes) of the Vue instance on every input This includes gain/loss of focus, etc.

.lazy modifier modified our v-model , so it only syncs after the change event. This reduces the number of times v-model tries to synchronize with the Vue instance, and in some cases, can also improve performance.

.number

Normally, even if the input is a number type, input will automatically change the input value into a string. One way to ensure that our values are treated as numbers is to use the .number modifier.

According to the Vue documentation, if input changes and parseFloat() cannot parse the new value, the last valid value entered will be returned.

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

.trim

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

Use v-model in custom components

In Vue, data binding has two main steps:

  1. Pass data from parent node
  2. Emit an event from the child instance to update the parent instance

v-model on custom components allows us to pass a prop and use an instruction to handle an event.

<custom-text-input v-model="value" />

<!-- IS THE SAME AS -->

<custom-text-input 
   :modelValue="value"
   @update:modelValue="value = $event"
/>

What exactly does this mean?

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

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

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

image.png

Use v-model in custom components

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

  1. Receive the value of v-model in props.
  2. When the corresponding value changes, send out an update event

Ok, let me declare first:

export default {
  props: {
    modelValue: String,
  }
}

Next, bind the modelValue to the required element. When the value changes, we will send the new value update:modelValue

In this way, two-way binding can be achieved.

image

Use skills of v-model

The above describes how to use v-model in custom components, now let’s take a look at some more advanced usage of the v-model

Use v-model multiple times for a component

v-model is not limited to only one per component. To use v-model multiple times, we just need to make sure that it is uniquely named and access it correctly in the child component.

v-model to the following components, here first named lastName :

<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>

Then, our internal subcomponents:

<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>

After running, you can see that both v-model can work normally:

image

Custom v-model modifier

There are some modifiers built into Vue, but these are far from enough, so sometimes we need to customize our own modifiers.

Suppose we want to create a modifier to remove all spaces in the entered text. We call it no-whitespace :

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

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

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

The first thing we need to do is to change the @input processor 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)'
/>

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

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

Works, perfect:

image

Summarize

I hope this article can teach you some new knowledge about Vue v-model.

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

~End, I’m Shuwanzhi, I’m going to clean the dishes, see you next time!


code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://learnvue.co/2021/01/everything-you-need-to-know-about-vue-v-model/

comminicate

There are dreams and dry goods. search 1617f3514c716f [Great Move to the World] Follow the brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68.1k 声望105k 粉丝