search
HomeWeb Front-endVue.jsTake you to have an in-depth understanding of v-model in vue2 and see how to make components support this syntax

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

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;,
      }
    }
  }
}

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></textarea> and <select></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;
  }
}

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

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

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

那么,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>

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

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

看看效果:

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

See all articles

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools