vuex使用方法:

根據(jù)vuex使用方法分析:
1、vuex使用是一個(gè)插件。
2、需要實(shí)現(xiàn)vuex構(gòu)造函數(shù)Store類。
實(shí)現(xiàn)方式如下:
(1)state狀態(tài)管理器的實(shí)現(xiàn):

把用戶的傳遞過來的state放在data里,實(shí)現(xiàn)響應(yīng)式數(shù)據(jù)。由于state不能讓用戶隨意訪問,所以需要對(duì)state加上一層封裝,變成$$state:oprions.state。
然后實(shí)現(xiàn)state的get和set方法:

(2)mutation和actions實(shí)現(xiàn):
1、首先在store類里面,將用戶的方法進(jìn)行存儲(chǔ)。

2、實(shí)現(xiàn)mutation和actions調(diào)用的對(duì)應(yīng)的方法:
commit方法:

實(shí)現(xiàn)原理看圖片備注,entry就是用戶在mutation里寫的方法。由于mutation可以直接修改state里的值,所以函數(shù)第一個(gè)值可以直接傳state。
dispath方法:

實(shí)現(xiàn)思路與commit方法大致一樣,但是entyr出口函數(shù)傳遞的第一個(gè)參數(shù)不一樣。dispath函數(shù)里傳遞的是上下文,可以傳遞this,this里面包含了commit(),getter()、因?yàn)閐ispatch不能直接修改state里的值,不能直接傳遞state。
getters方法:
const computed = {}
? ? this.getters = {}
? ? const store = this
? ? Object.keys(this._wapperedGetter).forEach(key => {
? ? ? const fn = this._wrappedGetters[key]
? ? ? computed[key] = function() {
? ? ? ? return fn(store.state)
? ? ? }
? ? ? Object.defineProperty(store.getters, key, {
? ? ? ? get: () => store._vm[key]
? ? ? })
? ? })
3、實(shí)現(xiàn)vuex插件安裝,加入mixin混入,延遲到vue實(shí)例出來后,進(jìn)行store掛載。
