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掛載椭盏。