vue 修飾符sync的使用
阿新 • • 發佈:2021-07-12
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');; } } })