2019-07-18 vue 理解和运用sync修饰符

官方文档里面说vue .sync 修饰符以前存在于vue1.0版本里,但是在在 2.0 中移除了 .sync 。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。(懵逼.....)

简单来讲sync 就是为了实现prop 进行“双向绑定”仅此而已(父对子,子对父,来回传)

看下案例就明白:一个实现父子数据双向绑定的例子

普通写法:

<text-document
    v-bind:title="doc.title"
    v-on:update:title="doc.title = $event"
></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进行“双向绑定”'
     }
  }, 
});

语法糖写法:

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


<script type="text/javascript"> 
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进行“双向绑定”'
     }
  }, 
})

参考:
官方解释:https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6
原出处:https://www.jianshu.com/p/e3b675e85ea9

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。