美文网首页
sync修饰符(他只是一个语法糖而已)

sync修饰符(他只是一个语法糖而已)

作者: 时光经年 | 来源:发表于2018-12-20 10:43 被阅读0次

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进行“双向绑定”'
     }
  }, 
})

相关文章

网友评论

      本文标题:sync修饰符(他只是一个语法糖而已)

      本文链接:https://www.haomeiwen.com/subject/icoekqtx.html