Vue:props.sync
參考資料
這篇文章會介紹到 Vue 的一個語法糖 .sync
,這個語法糖能夠讓我們在元件溝通上做到雙向綁定的功能,就讓我們看看是如何做到的吧!
Demo
Html
1 2 3 4 5 6 7 8 9
| <div id="app"> <div class="container"> <p>父元素:<input type="text" v-model="message"></p>
<hr>
<child-component :child-msg.sync="message"></child-component> </div> </div>
|
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| Vue.component('child-component', { template: ` <p>子元素:<input type="text" v-model="syncMsg"></p> `, props: { childMsg: String }, computed: { syncMsg: { get() { return this.childMsg }, set(val) { this.$emit('update:childMsg', val) } } } });
new Vue({ el: '#app', data: { message: '我要錢', } });
|
這樣就能夠做到組件之間的雙向綁定了。
結論
為什麼會說 .sync
是語法糖?其實可以看到程式碼當中也是使用 prop
、emit
來做到組件溝通的。
.sync
其實是 :child-msg="message" @update:childMsg="message = $event"
的縮寫。