vue modifier.sync

The .sync modifier first appeared in vue1.0 and was removed in vue2.0. Later, it was found that this modifier can still be used in actual projects. Therefore, .sync was reintroduced in vue2.3.0 as a syntax sugar.

:prop.sync="val" is syntactic sugar for :prop="val" and @update:prop="val => prop = val" For
example: < Child :id.sync="userId" /> is < Child : id="userId" @update:id="val => userId = val" Syntactic sugar for / >

// 父组件 parent.vue
<template>
    <div>
        <Child :id.sync="userId" />
    </div>
</template>

<script>
import Child from './child.vue'
export default {
    
    
    name: 'parent',
    componnets: {
    
     Child },
    data() {
    
    
        return {
    
    
            userId: 1
        }
    }
}
</script>

When a subcomponent needs to update the value of id

// 子组件 child.vue
<template>
    <div>
        <p>{
    
    {
    
     id }}</p>
        <button @click="add">id 加 1<button>
    </div>
</template>

<script>
export default{
    
    
    name: 'child',
    props: {
    
    id: Number},
    methods: {
    
    
        add(){
    
    
            let res = this.id + 1
            this.$emit('update:id', res)
        }
    }
}
</script>

Summary: The function of .sync is that when a child component modifies a prop, it will synchronize the binding of the parent component. This is somewhat similar to the v-model syntax.

Guess you like

Origin blog.csdn.net/qq_37600506/article/details/129685554