單向資料流 vs. 雙向資料流
資料流的概念經常是前端 Junior 面試的考題重點,也是理解三大框架時很重要的概念。
什麼是資料流、資料綁定?
資料流 data flow 跟 data binding 資料綁定 是否一樣?
從一些文章來看,經常會把這兩個單詞一起講,看起來像同個事情
React Official
React’s one-way data flow (also called one-way binding) keeps everything modular and fast.
React 官方文件,我個人是解讀為「 React 容易做到單向資料流、以及單向資料綁定」
Angular Official
So the Data Flow that we are referring to in the term Unidirectional Data Flow is the flow of application data that goes from the component classes into the output DOM data structures generated by the rendering process, during the top to bottom rendering sweep of the component tree.
Angular 官方把 data flow 解讀為組件與畫面的渲染過程(相當於 data binding)
我自己的理解是,嚴格來說他們所表達的是不同概念,這樣的想法讓我比較好想通關於「Vue 單向資料流、卻容易做到雙向綁定」這件事
data flow:組件間數據的流向,例如 React 中,props 只能由父給子
data binding :畫面 View 與 資料 Model 之間的綁定關係。例如 React 中,只能由 model 更新來渲染 view (單向綁定),但在 Vue 的表單操作可以由 view 來更新 model (v-model 提供的雙向綁定功能)
data flow 資料流
-- 目前三大框架都是單向資料流,這邊指的 Angular 是 2 以上的版本
-- Vue 1.0 、 AngularJS 為雙向資料流 (補:AngularJS 為所有 1.x 版本),子組件可以更新父組件的數據,同時代表變動的入口不只一個,如果沒有管理好就會難以 debug
-- 單向資料流優缺點:
優 - 只有一個變更入口 → 直觀、可維護性高
缺 - 資料流過用不到的階層,所以才需要 Redux、Vuex 協助、要多寫很多程式
data binding 資料綁定
畫面與資料之間的操作關聯有兩種:
- data model 的變動去更新 UI
- UI 的變動去更新 data model
若能做到其中之一,就是達成 one-way data binding 若兩個都能做到,則是 two-way data binding
因為我們對 React 還蠻熟悉,這邊分享比較不同的 Vue 的雙向綁定。
請先記得: Vue 同時支持單向綁定跟雙向綁定
Vue 的雙向綁定主要是針對表單事件的 v-model 語法,但其實 v-model 是結合 v-bind 跟 v-on 的語法糖,只不過是框架幫我們實現自動更新。
使用 v-model ,用戶在 UI 元件上的更改會直接同步到 model,而不是通過 onChange 事件去監聽。

參考資料
https://kuro.tw/posts/2019/07/31/談談前端框架/ https://devs.tw/post/40 https://blog.angular-university.io/angular-2-what-is-unidirectional-data-flow-development-mode/