Vue2.3 .sync 修饰符 父子组件传值与同步

72 阅读1分钟

原理篇

为了不让双向绑定显得混乱,约定:

// TextDocument.vue
export default {
    props: ['foo'],
    watch: {
        foo(val, oldVal){
            this.bar = val
        },
        bar(val, oldVal){
            this.$emit('update:foo', val)
        }
    },
    data(){
        return {
            bar: this.foo
        }
    }
}

<!-- Parent.vue -->
<text-document v-bind:title.sync="doc.title"></text-document>
<!-- 等同于 -->
<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>
<!--

应用篇

  1. v-model 对于单个属性绑定
  2. .sync 可绑定多个属性