高級 Vue 組件模式 (1)

寫在前頭

去年,曾經閱讀過一系列關於高級 react 組件模式的文章,今年上半年,又抽空陸陸續續地翻譯了一系列關於高級 angular 組件模式的文章,碰巧最近接手了一個公司項目,前端這塊的技術棧是 vue。我對於 vue 本身還是比較熟悉的,不過大多都是一些很簡單的個人項目,在構建相對比較複雜的應用中缺乏實踐經驗,就想着也搜搜類似題材的文章,漲漲知識。結果似乎沒有找到(其實也是有一些的,只不過不是和 react 和 angular 對比來寫的),不如就按照 react 和 angular 這兩個系列文章的思路,使用 vue 來親自實現一次吧。

由於三個框架的設計思想、語法都有比較大的區別,所以在實現過程中,均使用更符合 vue 風格的方式去解決問題,同時也提供一些對比,供讀者參考,如果觀點有誤,還望指正。

01 實現一個 toggle 組件

這個系列的文章的第一篇,都會從實現一個最簡單的 toggle 組件開始。

在 Vue 中,我們通過 data 來聲明一個 checked 屬性,這個屬性所控制的狀態代表組件本身的開關狀態,這個狀態會傳遞給負責渲染開關變換邏輯的 switch 組件中,關於 switch 組件,這裏不做過多介紹,你把它當作一個私有組件即可,其內部實現與該篇文章沒有太大的關聯。同時這個組件還擁有一個 on 屬性,用來初始化 checked 的狀態值。

通過在 switch 組件註冊原生 click 事件,toggle 組件還會觸發一個 toggled 事件,在 App 組件中,我們會監聽這個事件,並將其回傳的值打印到控制檯中。你可以下面的鏈接來看看這個組件的實現代碼以及演示:

總結

toggle組件的實現是一個很典型的利用單向數據流作爲數據源的簡單組件:

  • on 是單向數據源,checked 代表組件內部的開關狀態
  • 通過觸發 toggle 事件,將 checked 狀態的變化傳遞給父組件

目錄

React Angular Vue
Build a Toggle Component Build a Toggle Component Build a Toggle Component
Write Compound Components Write Compound Components todo
Make Compound React Components Flexible Write Compound Components
Make Enhanced React Components with Higher Order Components 03a Communicate Between Components Using Dependency Injection
03b Enhance Components with Directives
Handling Prop Namespace Clashes with Higher Order Components 04 Avoid Namespace Clashes with Directives
Improve Debuggability of Higher Order Components N/A
Handle Ref Props with Higher Order Components 05 Handle Template Reference Variables with Directives
Improve Unit Testability of Higher Order Components N/A
Handle Statics Properly with Higher Order Components N/A
Use Render Props with React 06 Use <ng-template>
Use Prop Collections with Render Props 07 Use Content Directives
Use Prop Getters with Render Props 08 Configure Content Directives
Use Component State Initializers 09 Use State Initializers
Make Controlled React Components with Control Props 10 Use Control Inputs
Implement a React Context Provider 11 Compound Components with Services
Implement a Higher Order Component with Render Props N/A
Re-render Descendants Through shouldComponentUpdateFinish 12 Re-render Descendants Through ChangeDetectorRef
Use Redux with Render Props 13 Use Ngrx with Directives
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章