Vue 中的 .sync 修饰符有什么用

140 阅读1分钟

Vue 中的.sync 修饰符有什么作用呢 下面来简单看看

在没有使用Vue 提供的 .sync 修饰符以前, 子组件修改父组件需要像下面这样去实现

// 子组件
<template>
    {{Data}}
    <button v-on="$emit('update.Data', Data - 10)">修改Data</button> 
</template>

<script>
export default {
    props: ["Data"]
}
</script>
// 父组件
<template>
    <div>
        {{father}}
        <Child :Data="father" v-on:update:Data="father = $event"/>
    </div>
</template>

<script>
import Child from './Child.vue'
export default {
    data(){
        return {
            father: 1000
        }
    },
    components: {Child}
}
</script>

使用Vue提供的.sync 语法

// 子组件不变
// 父组件
<template>
    <div>
        {{father}}
        <Child :Data.sync="father"/>
    </div>
</template>

<script>
import Child from './Child.vue'
export default {
    data(){
        return {
            father: 1000
        }
    },
    components: {Child}
}
</script>

在使用Vue提供的.sync 语法后, 可以看到, Vue 提供了一个 相当于我们自己实现了一个 v-on:update.Data 去自动更新在 父组件 中的 Data, 不需要我们手动去实现这样的一个方法, 无论是从代码可读性, 还是简化代码都提供了很大的方便