学习笔记(只是为了自己的记忆深刻,没有任何目的)
原生片段
import Vue from 'vue'
import Vuex from './vuex.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
})
使用vue的双向绑定机制实现简单的vuex
- 模拟$store.commit()
- 模拟$store.dispatch()
- 模拟$store.state.xxx
- 模拟getters
//1.挂载$store
//2.实现store
let Vue;
class Store{
constructor(options) {
//将state进行响应式处理
//访问 使用 this.$store.state.xxxx
this._vm = new Vue({
data:{
$$state:options.state,
},
});
this._mutations = options.mutations;
this._actions = options.actions;
//将this挂载到函数实列上
this.commit = this.commit.bind(this);
this.dispatch = this.dispatch.bind(this);
//模拟getter 计算state的计算属性
this.getters = {};
//模拟getters
options.getters && this.handleGetters(options.getters );
}
/**
* Object.keys 拿到getters中所有对象的key (也就是函数名)遍历
* 然后通过Object.defineProperty 进行数据劫持 将函数放到this.getters中 键值就是key
* 当用户进行访问的时候 通过get 去调用 getters[key]()//调用getters中的函数 并且将this.state传递进去
*/
handleGetters(getters){
Object.keys(getters).map((key)=>{
Object.defineProperty(this.getters,key,{
get:()=>{getters[key](this.state)},
})
})
}
get state(){
return this._vm._data.$$state;
}
set state(v){
console.error("state无法set");
}
//模拟mutations
commit(type,payload){
const entry = this._mutations[type];
if(!entry){
console.error("方法不存在");
}
entry(this.state,payload);
}
//模拟actions
dispatch(type,payload){
const entry = this._actions[type];
if(!entry){
console.error("方法不存在");
}
entry(this,payload);
}
}
//通过Vue中的混入mixin机制将vuex挂载到Vue中的实列中
const install =(_Vue)=>{
Vue = _Vue;
Vue.mixin({
beforeCreate() {
if(this.$options.store){
Vue.prototype.$store = this.$options.store;
}
}
})
}
export default {Store,install};