普通文組 2.5

「Vue:在子代元件實作雙向資料綁定」相關筆記

原始問題

如何在自訂的 vue component 中做出 v-model 的功能?

回答

參考 vue 的官方文件,v-model其實就是v-bind加上v-on的語法糖,故在一個自訂元件上做出 v-model(雙向資料綁定)的效果就等同「使用 props 將資料從親代傳入自訂元件,並從元件透過 emit 將資料變動傳送回親代」

展示:https://tzynwang.github.io/v-model-child-component-demo-HIGGS/ REPO:https://github.com/tzynwang/v-model-child-component-demo-HIGGS#vue-child-component-two-way-data-binding-demo

版本與環境

vue: 2.6.11

筆記

  • 實作思路:
    • 子代元件inputComponent.vue從親代接收資料componentValue
    • 在子代發生 input 事件時(@input)便呼叫方法emitValue,將使用者輸入的內容 emit 上親代,事件名稱為child-input-value-change
    • 親代在child-input-value-change發生時,呼叫childInputValueChange修改componentValue的值
    • 資料變動,驅動畫面重新渲染

參考文件