Table of Contents
1. v-model
2. .sync modifier
Summary
Home Web Front-end Vue.js What is the difference between modifier v-model and .sync? A brief analysis of differences and comparisons

What is the difference between modifier v-model and .sync? A brief analysis of differences and comparisons

Jul 11, 2022 pm 08:37 PM
vue vue.js v-model

What is the difference between modifier v-model and .sync? The following article will talk about the differences between v-model and .sync modifier. I hope it will be helpful to you!

What is the difference between modifier v-model and .sync? A brief analysis of differences and comparisons

In the daily development process, the v-model command is often used. Generally speaking, v-model Directives create two-way data binding on forms and elements, but v-model is essentially syntactic sugar. When it comes to syntax sugar, we have to mention another two-way binding syntax sugar that has similar functions to v-model, that is.sync modifier. Here is a summary of the two:

1. v-model

1. Function

I believe that friends who have used the vue framework will not be unfamiliar with this command. v-model is used to perform <input>, <textarea> </textarea>, <select></select> Two-way binding of data on elements. (Learning video sharing: vue video tutorial)

For example:

<template>
    <div >
        <input v-model="value" type="text"/>    //这里的v-model里面的value可以直接获取到用户的输入值
    </div>
</template>

<script>

export default {
    components: {},
    data() {
        return {
            value:"",    //这里定义的value变量可以直接将上面获取到的值进行操作
        };
      }, 
    }
</script>
<style  scoped>

</style>
Copy after login

When we enter a certain value in the input box, the value in the data below is You can directly get the value we entered without having to operate the dom element to obtain it.

1. Essence

v-model is essentially a syntactic sugar. Our habitual writing method is like this:

 <input v-model="value" type="text"/>
Copy after login

But actually the complete writing method is like this:

<input :value="value" @input="value=$event.target.value" type="text" />
Copy after login

By comparing the syntactic sugar and the original writing method, we can get: When adding the v-model attribute to the <input/> element, the value will be used as the attribute of the element by default, and the input event will be used as the trigger event for real-time delivery of value.

Note: Not all elements that can perform two-way data binding are input events!

3. Special usage

Generally, we use v-model mainly for two-way binding of data. It is very convenient to obtain the value entered by the user, but in some special cases, we can also use v-model for two-way binding of data between parent and child components.

<template>
    <div class="father">
        <Son v-model="str"/>
    </div>
</template>

<script>

import Son from &#39;@/components/Son.vue&#39;;    //引入子组件

export default {
    components: {Son},
    data() {
        return {
            str:"father"
        };
      },
    }
</script>
Copy after login

A father component and son component are defined here, and the son component is introduced into the father component, and v-model is bound to the son component to pass the value. At this time we need to receive and use this value in the son component:

<template>
    <div class="son">
        我是在son组件里接收到的值:{{value}}
    </div>
</template>
<script>
export default {
    components: {},
    props:{
        value:{
            type:String,
        },
      },
    }
</script>
Copy after login

Note: The value accepted here must be value. If you write it with another name, an error will be reported!

The parent component passes the value to the child component. The data cannot be modified directly in the child component. If you modify it directly, an error will be reported.

What is the difference between modifier v-model and .sync? A brief analysis of differences and comparisons

When When we need to modify this value, we need to pass it to the parent component for modification.

This requires defining a custom event on the child component in the parent component, through the child component $emit('custom event name','value') Method passes the value into the parent component.

But we cannot use custom events here because we use v-model to pass values, so we can only use input events to make modifications.

Use the $emit() method in the child component. Call the event in the parent component and pass the value

<template>
    <div class="son">
        我是在son组件里接收到的值:{{value}}
        <button @click="handleClick">click</button>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        return {
            str:&#39;son&#39;
        };
    },
    props:{
        value:{
            type:String,
        },
    },
    methods: {
        handleClick(){
            this.$emit(&#39;input&#39;,this.str)
        }
    },
    }
</script>
Copy after login

This completes the bidirectional data between the parent and child components. Binding effect

2. .sync modifier

1. Function

.sync The modifier can realize two-way binding between parent and child components, and can realize the child component to modify the value of the parent component synchronously. Compared with v-model, the sync modifier is Much simpler:

2. The essence

    //正常父传子
    <Son :a="num" />
    
    //加上sync之后的父传子
    <Son :a.sync="num" />
    
    //它等价于
    <Son :a="num" @update:a="val=>a=val" />
    
    //相当于多了一个事件监听,事件名是update:a,
    //回调函数中,会把接收到的值赋值给属性绑定的数据项中。
Copy after login

The value passing and receiving here are not the same as the normal parent component passing value to the child component. The only difference is that when the subcomponent returns a value, the event name called by $emit must be update:property name. If the event name is written incorrectly, no error will be reported, but there will be no error at that time. Change, this needs to be noted.

Summary

v-model and .sync: The same thing: they are both syntax sugar, and they can realize data communication in parent-child components.

Differences: Different formats, v-model="num" :num.sync="num"

v-model:@input value :num.sync:@update:num

Also, v-model can only be used once, and .sync can be used multiple times.

[Related video tutorial recommendations: vuejs entry tutorial, web front-end entry]

The above is the detailed content of What is the difference between modifier v-model and .sync? A brief analysis of differences and comparisons. 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
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

React, Vue, and the Future of Netflix's Frontend React, Vue, and the Future of Netflix's Frontend Apr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

How to implement component jump for vue How to implement component jump for vue Apr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and &lt;router-view&gt; components to perform hyperlink jump, and specify the :to attribute as the target path. Use the &lt;router-view&gt; component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

See all articles