Vuex 簡介
栏目: JavaScript · 发布时间: 7年前
内容简介:若 Component 間很單純,我們使用 Prop 與 Event 溝通即可,但若 component 間很複雜,而彼此之間又有 data 改變造成連動,使用 Prop 與 Event 就會很麻煩,此時就要使用 Vuex。Vue 2.5.17Vue CLI 3.0.0
若 Component 間很單純,我們使用 Prop 與 Event 溝通即可,但若 component 間很複雜,而彼此之間又有 data 改變造成連動,使用 Prop 與 Event 就會很麻煩,此時就要使用 Vuex。
Version
Vue 2.5.17
Vue CLI 3.0.0
Component 間溝通
標準的 component 溝通方式:
v-bind v-on
-
若 component 架構較複雜,則 component 間的溝通若靠 prop 與 event 會很麻煩,必須一層一層往上
$emitevent,然後再向下一層一層傳prop -
假如左側第二層是
購物列表,第三層是購物商品,第四層是購物按鈕 -
假如右側第二層是右上角
標題區塊,第三層是購物數量 -
若希望 click
購物按鈕,會去改變購物數量,由於 component hierarchy 很深,要靠 Event 與 Prop 機制就會很麻煩
Event Bus Pattern
購物按鈕 購物數量
若我們希望 購買商品 的狀態 (變數),不是存在 購物按鈕 component 內,也不是存在 購物數量 component 內,而是存在一個 統一管理狀態 的地方,此時 Event Bus 就不適用
Vuex
- 將
購買商品存在Store(Vuex) 的State內 - 透夠 commit
Mutation去改變State - 若
State改變,則所有 compnent 會自動改變 (computed) - Vuex 符合 Unidirectional Dataflow,都只是 commit
Mutation
Q : Event Bus 與 Vuex 有什麼差別 ?
-
購物按鈕component 是 emit event 去修改購物數量component 的狀態 (data) -
購物按鈕component 是 commitMutation去修改全域Store的狀態 (data)
- Vue Component : 負責 dispatch
Action或 commitMutation - Action : 處理 Side Effect 地方,呼叫
API,然後 commitMutation - Mutation : 修改 data 的地方,負責 mutate
State,為 Pure Function - State : 儲存 data 的地方,當
State被更改後,會自動 renderComponent(也是 Side Effect,但由 Vue 處理) - Devtools : 可由 Chrome 的 Devtools 觀察
Mutation,方便 debug
Summary
Vuex :
- 讓 component 之間可以溝通
- 但 component 之間不是直接溝通,而是透過 global state
- 由
Action、Mutation與State三部分組成
適用時機
- Component 很少互相溝通,上下傳遞就很夠用:Prop + Event
- Component 會互相溝通,但情境很固定,數量也很少:Event Bus
- Component 常會跨 component 傳遞狀態:Vuex
- 需要 Global 管理狀態 : Vuex
Conclusion
- Vuex 觀念來自於 React 的 Redux, 是使用 Functional Programming 思維所設計的架構,並不是 Object Oriented Programming 思維下的產物
- 因為對 state 處理想使用 Pure Function,所以有了 Mutation 機制,但總還是要有處理 Side Effect,所以有了 Action 機制
- 若沒有 Side Effect,Component 可直接 commit Mutation
- 若有 Side Effect,Component 要先 dispatch Action,然後再由 Action commit Mutation
- 並不是一定得用 Vuex,但若 component 間互動複雜,或需要 global 管理狀態時,就該使用 Vuex
Reference
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Game Programming Patterns
Robert Nystrom / Genever Benning / 2014-11-2 / USD 39.95
The biggest challenge facing many game programmers is completing their game. Most game projects fizzle out, overwhelmed by the complexity of their own code. Game Programming Patterns tackles that exac......一起来看看 《Game Programming Patterns》 这本书的介绍吧!