vue .sync修饰符

在一些情况下,我们可能会需要对一个prop(父子组件传递数据的属性)进行‘双向绑定’,vue重新引入.sync修饰符,是作为编译时的一个语法糖,它会被扩展为一个自动更新父组件属性的v-on监听器。

普通写法:

<text-decoment v-bind:title='title' v-on:update:title='title=$event'></text-document>

语法糖写法:

<text-document v-bind:title.sync="doc.title" ></text-document>

Vue.component('text-document', {

  props: ['title'],

  template: ` <div> <button @click='setNewTitle'>更新标题</button> </div> `,

  methods:{

    setNewTitle:function(){//手动进行更新父组件中的值

    this.$emit('update:title', '这步操作修改标题实现prop双向绑定')

  }

}

})

var vm = new Vue({ el:'#app', data:{ doc:{ title:'对prop进行“双向绑定”' } }, });

.sync也可以是对象,绑定多个数据,vue会为每个数据绑定事件,但不能是表达式,表达式临界状态比较多,不好处理

demo:

<text-document v-bind:obj.sync="obj" ></text-document>

Vue.component('text-document', {

  props: ['obj'],

  template: ` <div> <button @click='setNewTitle'>更新标题</button> </div> `,

  methods:{

    setNewTitle:function(){//手动进行更新父组件中的值

    this.$emit('update:obj', '这步操作修改标题实现prop双向绑定')

  }

}

})

 

posted on 2020-09-23 18:02  半夏微澜ぺ  阅读(163)  评论(0编辑  收藏  举报