使用vue模拟VueX

学习笔记(只是为了自己的记忆深刻,没有任何目的)
原生片段

import Vue from 'vue'
import Vuex from './vuex.js'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {},
	mutations: {},
	actions: {},
	modules: {}
})

使用vue的双向绑定机制实现简单的vuex

  1. 模拟$store.commit()
  2. 模拟$store.dispatch()
  3. 模拟$store.state.xxx
  4. 模拟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};
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值