index.js
import Vue from 'vue'
import Vuex from './kvuex'
// 實現(xiàn)一個插件:$store掛載
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 1
},
mutations: {
add(state) {
// state怎么來的
state.count++
}
},
getters: {
doubleCount: state => {
return state.count * 2;
}
},
actions: {
asyncAdd({commit}) {
setTimeout(() => {
commit('add')
}, 1000);
}
},
modules: {
}
})
vuex.js
// 1.實現(xiàn)一個插件:實現(xiàn)Store,掛載$store
// 引用Vue構(gòu)造函數(shù)
let Vue;
class Store {
constructor(options){
// 只要放到data上,即成為響應(yīng)式的數(shù)據(jù)
// vm.data.count vm.count
this._vm = new Vue({
data: {
$$state: options.state
}
})
// 保存mutaions
this._mutations = options.mutations;
this._actions = options.actions;
// 綁定commit忙上、dispatch方法中的this到Store實例上
const store = this;
const {commit, dispatch} = store;
this.commit = function boundCommit(type, payload) {
commit.call(store, type, payload)
}
this.dispatch = function boundDispatch(type, payload) {
dispatch.call(store, type, payload)
}
}
// 只讀state砾层,可以獲取數(shù)據(jù)
get state() {
return this._vm._data.$$state
}
set state(v) {
console.error('表改鞭缭,這里不能修改state荧关,想改請使用replaceState()');
}
// commit: type-mutation類型够颠,payload-參數(shù)
commit(type, payload) {
const entry = this._mutations[type]
if (!entry) {
console.error('unknown mutation type:'+type);
return
}
// 在這可以做一些攔截處理
// 傳遞state進去
entry(this.state, payload)
}
// action: type-action類型乔煞,payload-參數(shù)
dispatch(type, payload) {
const entry = this._actions[type]
if (!entry) {
console.error('unknown mutation type:'+type);
return
}
// 在這可以做一些攔截處理
// 傳遞上下文進去吁朦,實際上就是Store實例
entry(this, payload)
}
}
function install(_Vue) {
Vue = _Vue
// 全局混入
Vue.mixin({
beforeCreate() {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store
}
}
})
}
// 下面導(dǎo)出的對象等同于Vuex,實例化時使用new Vuex.Store
export default {Store,install}