本集內容:Store 與 Context 介紹
Svelte 內建 store 機制,除了不用戰 redux 之外,store 本身的功能也很強大,透過 svelte 的 `$` 功能還可以達到方便取值的效果,也可以搭配其他函式庫如 Rx.js 做整合。
Store 也可以在 Svelte 元件外操作,方便切分業務邏輯。
第 12 屆 IT 鐵⼈賽30 天從 0 到 1 學 SvelteDay6 - Context 與 Store
View Slide
第 12 屆 IT 鐵⼈賽本⽇⽬標認識 Svelte 當中 Store 與 Context 的⽤法
第 12 屆 IT 鐵⼈賽什麼時候⽤ store資料經常更動且可能會跨元件使⽤不想參雜太多業務邏輯在元件當中想透過其他 Library 達到 reactive 效果
第 12 屆 IT 鐵⼈賽Store API可在元件外宣告,依功能分為 readable, writable, derived
第 12 屆 IT 鐵⼈賽writable可以透過 update 或 set 從外部修改 store 的值
第 12 屆 IT 鐵⼈賽readable只能從內部修改 store 的資料(e.g 聊天室)
第 12 屆 IT 鐵⼈賽derived接收 1 ⾄多個 store 並且作加⼯
第 12 屆 IT 鐵⼈賽.subscribe()所有的 svelte store 都有 subscribe ⽅法
第 12 屆 IT 鐵⼈賽Svelte 整合 - $在變數前加入 $ 可以⾃動訂閱 store同時處理 unsubscribe 邏輯
第 12 屆 IT 鐵⼈賽搭配 Rx 與 Svelte 整合!
第 12 屆 IT 鐵⼈賽get拿到 store 內的值
第 12 屆 IT 鐵⼈賽什麼時候⽤ Context資料幾乎不會變動(使⽤者資料、theme)跨元件溝通時
第 12 屆 IT 鐵⼈賽與 store 的不同之處沒有 reactive 效果(如 subscribe, unsubscribe)需要在 Svelte 元件中使⽤才有效果只會作⽤在 Svelte 的元件樹當中Svelte 會去找尋離元件距離最近的 context
第 12 屆 IT 鐵⼈賽getContext, setContext