如何理解Vue的.sync修饰符

113 阅读1分钟

Vue 规定,组件是不能修改 props 得到的外部数据,但 $emit可以触发事件,并传参,$event可获取$emit的参数。

vue 修饰符.sync的功能是:当一个子组件改变了一个 props的值时,这个变化也会同步到父组件中所绑定。

示例

<div id="app">
    <div>{{bar}}</div>
    <my-comp :foo.sync="bar"></my-comp>
    <!-- <my-comp :foo="bar" @update:foo="bar=$event"></my-comp> -->
</div>
<script>
    Vue.component('my-comp', {
        template: '<div @click="increment">点我+1</div>',
        data: function() {
            return {copyFoo: this.foo}
        },
        props: ['foo'],
        methods: {
            increment: function() {
                this.$emit('update:foo', this.copyFoo+1);
            }
        }
    });
    new Vue({
        el: '#app',
        data: {bar: 0}
    });
</script>

<my-comp :foo="bar" @update:foo="bar=$event"></my-comp> 等价于<my-comp :foo.sync="bar"></my-comp>

.sync修饰符 就是一个语法糖。