Table of Contents
Read this article
1. The essence of v-model is syntactic sugar.
Is it two-way binding or one-way data flow? 2.1
Is it two-way binding?
a one-way data flow?
四、如何让你开发的组件支持 v-model
五、demo和源码
Home Web Front-end Vue.js Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

Jan 04, 2022 pm 07:11 PM
v-model vue2

This article will take you to understand v-model in vue2, see whether v-model is two-way binding or one-way data flow, and how to make the components you develop support v-model. I hope it will be helpful to everyone.

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

Read this article

You will:

  • Understand: What is v-model Syntactic sugar? vue2 What special processing has been done to native components?
  • Find out: v-model Is it one-way data flow or two-way data binding?
  • Figure out: v-model What are the "side effects" beyond syntactic sugar?
  • Learn how to make your components support v-model syntax.

1. The essence of v-model is syntactic sugar.

v-model is essentially just syntactic sugar. It is responsible for listening to user input events to update data and perform some special processing for some extreme scenarios. 』 --Official documentation. [Related recommendations: vue.js tutorial]

What is syntactic sugar?

Syntax sugar, simply put, is "convenient writing".

In most cases, v-model="foo" is equivalent to :value="foo" plus @input ="foo = $event";

<!-- 在大部分情况下,以下两种写法是等价的 -->
<el-input v-model="foo" />

<el-input :value="foo" @input="foo = $event" />
Copy after login

Yes, in most cases this is true.

But there are exceptions:

  • vue2 provides the model attribute to the component, allowing users to customize The prop name of the passed value and the event name of the updated value . I’ll skip this for now and will go into details in Section 4.

  • For native html native elements, vue has done a lot of "dirty work" in order to make us ignore it html Differences in API. The left and right writing methods of the following elements are equivalent:

  • textarea Element:

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

  • select Drop-down box:

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

  • ##input type='radio' Radio button:

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

    ##input type='checkbox'
  • Multiple checkbox:

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntaxIn terms of programming thinking, this way of helping users "hide details" is called

encapsulation

. 2. Is v-model just syntactic sugar? (Trivia)

v-model

is not only syntactic sugar, it also has side effects.

The side effects are as follows:
If

v-model is bound to a property that does not exist on the responsive object, then vue will quietly Simply add this property and make it responsive. For example, look at the following code:

// template中:
<el-input v-model="user.tel"></el-input>
// script中:
export default {
  data() {
    return {
      user: {
        name: &#39;公众号: 前端要摸鱼&#39;,
      }
    }
  }
}
Copy after login

The

user.tel

attribute is not defined in the responsive data, but the template But v-model is used to bind user.tel. Guess what happens when you enter? See the effect:


Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax Reveal the answer:

tel

attribute will be added to user , and tel this attribute is still responsive. This is the effect of "side effects", have you learned it?

3.

v-model

Is it two-way binding or one-way data flow? 2.1

v-model

Is it two-way binding?

Yes, the official said yes.

『You can use the v-model directive in forms

, <textarea> and <select> Create two-way data binding on the element. 』——vue2 official document2.2 Is

v-model

a one-way data flow?

Yes, it is even a typical paradigm for one-way data flow.

Although the official did not clearly state this, we can figure out the relationship between the two.

What is a single data flow?
  • A child component cannot change the
prop

attribute passed to it by the parent component. The recommended approach is for it to throw an event and notify the parent component to change the bound value on its own.

    v-model
  • How to do it?
v-model

The approach is completely consistent with single data flow. Even more, it provides a specification on naming and event definition. <p>众所周知 <code>.sync 修饰符是单向数据流的另一个典型范式。

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

『单向数据流』总结起来其实也就8个字:『数据向下,事件向上』。

四、如何让你开发的组件支持 v-model

虽然不想说,但这确实是高频面试题。

在定义 vue 组件时,你可以提供一个 model 属性,用来定义该组件以何种方式支持 v-model

model 属性本身是有默认值的,如下:

// 默认的 model 属性
export default {
  model: {
    prop: &#39;value&#39;,
    event: &#39;input&#39;
  }
}
Copy after login

也就是说,如果你不定义 model 属性,或者你按照当面方法定义属性,当其他人使用你的自定义组件时,v-model="foo" 就完全等价于 :value="foo" 加上 @input="foo = $event"

如果把 model 属性进行一些改装,如下:

// 默认的 model 属性
export default {
  model: {
    prop: &#39;ame&#39;,
    event: &#39;zard&#39;
  }
}
Copy after login

那么,v-model="foo" 就等价于 :ame="foo" 加上 @zard="foo = $event"

没错,就是这么容易,让我们看个例子。

先定义一个自定义组件:

<template>
<div>
  我们是TI{{ ame }}冠军
  <el-button @click="playDota2(1)">加</el-button>
  <el-button @click="playDota2(-1)">减</el-button>
</div>
</template>
<script>
export default {
  props: {
    ame: {
      type: Number,
      default: 8
    }
  },
  model: { // 自定义v-model的格式
    prop: &#39;ame&#39;, // 代表 v-model 绑定的prop名
    event: &#39;zard&#39; // 代码 v-model 通知父组件更新属性的事件名
  },
  methods: {
    playDota2(step) {
      const newYear = this.ame + step
      this.$emit(&#39;zard&#39;, newYear)
    }
  }
}
</script>
Copy after login

然后我们在父组件中使用该组件:

// template中
<dota v-model="ti"></dota>
// script中
export default {
  data() {
    return {
      ti: 8
    }
  }
}
Copy after login

看看效果:

Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

让你的组件支持 v-model 就这么容易。

五、demo和源码

获取源码请访问github 

https://github.com/zhangshichun/blog-vue2-demos/tree/master/src/views/about-v-model

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Take you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
What is the difference between the life cycle execution order in vue2 and vue3 What is the difference between the life cycle execution order in vue2 and vue3 May 16, 2023 pm 09:40 PM

Difference in life cycle execution order between vue2 and vue3 Life cycle comparison The execution order in vue2 beforeCreate=>created=>beforeMount=>mounted=>beforeUpdate=>updated=>beforeDestroy=>destroyed The execution order in vue3 setup=>onBeforeMount=>onMounted=> onBeforeUpdate=>onUpdated=>onBeforeUnmount=&g

How to use v-model.number to implement data type conversion of input boxes in Vue How to use v-model.number to implement data type conversion of input boxes in Vue Jun 11, 2023 am 08:54 AM

In Vue, v-model is an important instruction used to implement two-way binding. It allows us to easily synchronize user input to Vue's data attribute. But in some cases, we need to convert the data, such as converting the string type input by the user into a numeric type. In this case, we need to use the .number modifier of v-model to achieve this. Basic usage of v-model.number v-model.number is a modification of v-model

Quickly understand the Vue2 diff algorithm (detailed graphic explanation) Quickly understand the Vue2 diff algorithm (detailed graphic explanation) Mar 17, 2023 pm 08:23 PM

The diff algorithm is an efficient algorithm that compares tree nodes at the same level, avoiding the need to search and traverse the tree layer by layer. So how much do you know about the diff algorithm? The following article will give you an in-depth analysis of the diff algorithm of vue2. I hope it will be helpful to you!

Using v-model's two-way binding in Vue to optimize application data performance Using v-model's two-way binding in Vue to optimize application data performance Jul 17, 2023 pm 07:57 PM

Using v-model's two-way binding in Vue to optimize application data performance In Vue, we often use the v-model directive to achieve two-way binding between form elements and data. This two-way binding greatly simplifies the development process and improves user experience. However, since v-model needs to listen to the input event of the form element, this two-way binding may cause certain performance problems when the amount of data is large. This article will introduce how to optimize data performance when using v-model and provide a

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Aug 19, 2023 pm 08:46 PM

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Introduction: Two-way data binding is a very common and powerful feature when developing with Vue. However, sometimes we may encounter a problem, that is, when we try to use v-model for two-way data binding, we encounter an error. This article describes the cause and solution of this problem, and provides a code example to demonstrate how to solve the problem. Problem Description: When we try to use v-model in Vue

How to solve Vue error: Unable to use v-model correctly for two-way data binding How to solve Vue error: Unable to use v-model correctly for two-way data binding Aug 25, 2023 pm 04:13 PM

How to solve Vue error: Unable to correctly use v-model for two-way data binding Introduction: Vue is a popular front-end framework that provides many convenient functions, including the v-model directive for implementing two-way data binding. However, sometimes we may encounter some errors when using v-model, especially when dealing with complex data structures. This article will introduce several common v-model errors and provide solutions and code examples. Error: Two-way binding of v-model and object properties

Solve Vue error: Unable to use v-model for two-way data binding Solve Vue error: Unable to use v-model for two-way data binding Aug 25, 2023 pm 04:49 PM

Solve Vue error: Unable to use v-model for two-way data binding. When developing with Vue, the v-model instruction is often used to achieve two-way data binding, but sometimes we encounter a problem when using v- An error will be reported when using the model, and two-way data binding cannot be performed correctly. This may be due to some common errors. Below I will introduce several common situations and corresponding solutions. The props attribute of the component is not set correctly. When we use the component, if we need to pass v-

Detailed examples of how to use the v-model directive in Vue Detailed examples of how to use the v-model directive in Vue Aug 10, 2022 pm 05:38 PM

You can use the v-model directive in Vue to achieve two-way data binding. This article will take you through the v-model directive. I hope it will be helpful to you!

See all articles