vue 修饰符 .sync

.sync 修饰符最先出现在 vue1.0 中,vue2.0 移除,后续在实际项目中发现这个修饰符还是有可使用的地方。因此在 vue2.3.0 时重新引入 .sync,作为一个语法糖。

:prop.sync=“val” 是 :prop=“val” 与 @update:prop=“val => prop = val” 的语法糖
例如: < Child :id.sync=“userId” / > 是 < Child :id=“userId” @update:id=“val => userId = val” / > 的语法糖

// 父组件 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>

当子组件需要更新 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>

总结:.sync 的功能就是当子组件修改一个 prop 时,会同步父组件的绑定,这个有点类似于 v-model 语法

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/129685554