vue 修饰符sync的使用

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

vue官方文档介绍 .sync修饰符

不使用.sync之前的写法

// 父组件
<parent :message=“bar” @update:message=“updateMessage”>
// js更新prop的值
updateMessage(val){
   this.bar = val;
}

使用.sync修饰符的写法

// 父组件
<parent :message.sync=“bar”>
// 子组件[]()
this.$emit('update:message',valc);

当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

 // doc的数据结构
doc  = {
  title: '',
  label: ''
}
// 父组件
<text-document v-bind.sync="doc"></text-document>

 // 子组件
Vue.component('text-document', {
 template: `
  <span>
   <input
    ref="input"
    :value="title"
    @change="handleChange"
   >
  </span>
 `,
 props: ['title',  'label'], // 
 methods:{
            handleChange(val){
                this.$emit('update:label',val);
                this.$emit('update:title',val + 'title');;
            }
        }
})
原文地址:https://www.cnblogs.com/whkl-m/p/15003230.html