這個關鍵字在v2.3.0+ 新增,注意帶有 .sync
修飾符的 v-bind
不能和表達式一起使用 (例如 v-bind:title.sync=”doc.title + ‘!’”
是無效的)。說白了他就是子組件改變父組件DATA的一種方法,但是個人覺得要慎用吧,不然有容易污染組件數據的隱患,
可以運行一下示例代碼,參考vue dev tool ,就會明白
father.vue:
<template> <div class="hello"> //input實時改變wrd的值, 並且會實時改變box里的內容 <input type="text" v-model="wrd"> <hr> 這是name---{{sname}} <!-- 不寫sync不更新父組件數據,變成了單向的父組件傳值給子組件的寫法 --> <box :word.sync="wrd" :sname.sync="sname" ></box> </div> </template> <script> import box from './child.vue' //引入box子組件 export default { name: 'HelloWorld', data() { return { wrd: '', sname:'zs', age:12 } }, components: { box } } </script>
child.vue
<template> <div class="hello"> <div class="ipt"> <hr> --------------------------------------------- <br> <input type="text" v-model="str"> </div> //word是父元素傳過來的 <br> <h2>{{ word }}</h2> <br> //sname也是 <br> <h2>{{ sname }}</h2> </div> </template> <script> export default { name: 'box', data() { return { str: '', } }, props: { word: { type:String, default:'' }, sname:{ type:String, default:'ls' } }, watch: { str: function(newValue, oldValue) { //每當str的值改變則發送事件update:sname , 並且把值傳過去,這時會修改父組件的data值 this.$emit('update:sname', newValue); //如果多個值又不想用object,可以多次emit this.$emit('update:word', newValue+'1'); } } } </script>