实现vuex源码,手写

实现vuex源码,手写

Vuex 是专门为 Vue.js 应用程序开发的状态管理模式 + 库,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

第一步:定义初始化Store类

创建文件夹store/vuex.js

1.定义 Store 类

  • 创建一个名为 Store 的类,它接受一个 options 对象作为参数。
  • options 对象中,包含 state(应用的状态)、mutations(同步更改状态的方法)、actions(异步操作或包含任意异步操作的方法)、以及 getters(从 state 中派生出一些状态的方法)。
let Vue;
class Store{constructor(options) {}
}

2.初始化 Vue 实例

  • Store 类的构造函数中,使用 new Vue({ data: { $$state: options.state } }) 创建一个 Vue 实例,用于响应式地存储状态。这里使用 $$state 作为属性的名称是为了避免与 Vue 实例自身的 state 属性冲突,但这不是必须的,只是一个命名约定。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})}
}

3.存储 mutations 和 actions

  • options.mutationsoptions.actions 分别存储在 this._mutationsthis._actions 中。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actions}
}

4.绑定 commit 和 dispatch 方法

  • 使用 Function.prototype.bind 方法将 commitdispatch 方法绑定到 Store 实例上,以确保在回调函数中 this 指向正确。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)}
}

5.初始化 getters

  • 创建一个空对象 this.getters 用于存储 getter 方法。
  • 如果 options.getters 存在,则调用 this.handleGetters(options.getters) 方法来初始化 getters。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)this.getters = {}options.getters && this.hanleGetters(options.getters)}
}

第二步:实现 handleGetters 方法和其他 Store 方法

1.实现 handleGetters 方法

  • handleGetters 方法中,遍历 getters 对象的键。
  • 使用 Object.definePropertythis.getters 对象上定义每个 getter 属性,其 get 方法返回 getters[key](this.state) 的结果。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)this.getters = {}options.getters && this.hanleGetters(options.getters)}handleGetters(getters){Object.key(getters).map((key)=>{Object.defineProperty(this.getters,key,get: () => getters[key](this.state)})})}
}

2.实现 state 的 getter 和 setter

  • 使用 get state() 方法来访问 Vue 实例中存储的状态。
  • 使用 set state(v) 方法来防止直接修改状态(虽然在这里,setter 只是打印了一个错误消息)。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)this.getters = {}options.getters && this.hanleGetters(options.getters)}handleGetters(getters){Object.key(getters).map((key)=>{Object.defineProperty(this.getters,key,get: () => getters[key](this.state)})})}//get setget state(){return this._vm.data.$$state}set state(v) {console.error("please provide");}
}

3.实现 commit 方法

  • commit 方法用于触发 mutations,它接受一个 type(mutation 的类型)和一个可选的 payload(传递给 mutation 的数据)。
  • 根据 typethis._mutations 中找到对应的 mutation 方法,并调用它,传入 this.statepayload
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)this.getters = {}options.getters && this.hanleGetters(options.getters)}handleGetters(getters){Object.key(getters).map((key)=>{Object.defineProperty(this.getters,key,get: () => getters[key](this.state)})})}//get setget state(){return this._vm.data.$$state}set state(v) {console.error("please provide");}//commitcommit(type,value){const entry = this._mutations[type]if(!entry){console.error("please provide");}entry(this.state,value)}
}

4.实现 dispatch 方法:

  • dispatch 方法用于触发 actions,它的工作原理与 commit 类似,但通常用于处理异步操作。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)this.getters = {}options.getters && this.hanleGetters(options.getters)}handleGetters(getters){Object.key(getters).map((key)=>{Object.defineProperty(this.getters,key,get: () => getters[key](this.state)})})}//get setget state(){return this._vm.data.$$state}set state(v) {console.error("unknown mutation type");}//commitcommit(type,value){const entry = this._mutations[type]if(!entry){console.error("please provide");}entry(this.state,value)}//dispatchdispatch(type,value){const entry = this._actions[type]if(!entry){console.error("unknown action type")}entry(this.state,value)}
}

第三步:安装现在自定义vuex插件,需要一个install方法

  • 创建一个名为 install 的函数,它接受一个 Vue 构造函数作为参数。
  • install 函数中,将 Vue 构造函数存储在全局变量 Vue 中。
  • 使用 Vue.mixin 方法来全局注册一个 beforeCreate 钩子,该钩子会在每个 Vue 组件实例创建之前被调用。
  • 在 beforeCreate 钩子中,检查 this.$options.store 是否存在,如果存在,则将其赋值给 Vue.prototype.$store,这样在任何 Vue 组件中都可以通过 this.$store 访问到 store 实例。
let Vue;
class Store{constructor(options) {this._vm = new Vue({data:{$$state:options.state}})this._mutations = options.mutationsthis._actions = options.actionsthis.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)this.getters = {}options.getters && this.hanleGetters(options.getters)}handleGetters(getters){Object.key(getters).map((key)=>{Object.defineProperty(this.getters,key,get: () => getters[key](this.state)})})}//get setget state(){return this._vm.data.$$state}set state(v) {console.error("unknown mutation type");}//commitcommit(type,value){const entry = this._mutations[type]if(!entry){console.error("please provide");}entry(this.state,value)}//dispatchdispatch(type,value){const entry = this._actions[type]if(!entry){console.error("unknown action type")}entry(this.state,value)}
}Store.install = (_vue)=>{Vue = _vueVue.mixin({beforeCreate(){if(this.$options.store){Vue.prototype.$store = this.$options.$store}}})
}

第四步:导出install,Store

let Vue;
class Store {constructor(options) {this._vm = new Vue({data: {$$state: options.state,},});this._mutations = options.mutations;this._actions = options.actions;this.commit = this.commit.bind(this);this.dispatch = this.dispatch.bind(this);this.getters = {};options.getters && this.handleGetters(options.getters);}handleGetters(getters) {console.log(Object.keys(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("please provide");}commit(type, payload) {console.log(type, payload)const entry = this._mutations[type];if (!entry) {console.error("unknown mutation type: " + type);}entry(this.state, payload);}dispatch(type, payload) {console.log(this._actions[type]);const entry = this._actions[type];if (!entry) {console.error("unknown mutation type: " + type);}entry(this.state, payload);}
}
const install = (_Vue) => {Vue = _Vue;Vue.mixin({beforeCreate() {if (this.$options.store) {Vue.prototype.$store = this.$options.store;}},});
};
export default {Store,install,
};

第五步:创建store/index.js

import Vue from 'vue'
// 引入自己的写的vuex,里面有一个对象{install},当你use时,会自动调用这个方法
import Vuex from './vuex.js'
Vue.use(Vuex)
//需要创建一个仓库并导出
//当new的时候,给Vuex.js中传入了一堆的东西
export default new Vuex.Store({state: {name: 1},//getters中虽然是一个方法,但是用时,可以把他当作属性getters: {   // 说白了,就是vue中data中的computedpowerCount(state) {return state.name * 2},},// 改变状态:异步请求数据  事件 mutations: {add(state) {state.name++}},actions: {add(state) {setTimeout(() => {console.log(state)state.name = 30}, 1000);}}
})

第六步:在main中挂载store

/* eslint-disable vue/multi-word-component-names */
import Vue from 'vue'
import App from './App.vue'
import store from "./store.js"
Vue.config.productionTip = falsenew Vue({name:"main",store,render: h => h(App),
}).$mount('#app')

第七步:如何使用store

和vuex一样的用法,语法一样

<template><div>{{ $store.state.name }}{{ $store.getters.powerCount }}<button @click="add">123</button></div>
</template>
<script>
export default {name: "app",data() {return {}},methods:{add(){this.$store.commit('add')// this.$store.dispatch('add')console.log(this.$store.getters.powerCount)this.$store.handleGetters.powerCount}},mounted() { console.log(this.$store.state.name)}
}
</script>{{ $store.state.name }}{{ $store.getters.powerCount }}<button @click="add">123</button></div>
</template>
<script>
export default {name: "app",data() {return {}},methods:{add(){this.$store.commit('add')// this.$store.dispatch('add')console.log(this.$store.getters.powerCount)this.$store.handleGetters.powerCount}},mounted() { console.log(this.$store.state.name)}
}
</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/57531.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++:模板的特化与分离编译

之前我们在介绍模板的时候仅仅是简单的介绍了模板的用法&#xff0c;本篇文章我们来详细的介绍下模板中比较重要的几个点。 一&#xff0c;非类型模板参数 我们之前的c中&#xff0c;会将经常使用的而又确保在我们程序的运行过程中值不会改变的值进行#define&#xff1a; #d…

初入编程之路,启航代码海

#1024程序员节|征文# 前言 今天又是1024程序员节了&#xff0c;第一次听说这个节日是在我在23年刚刚上大一的时候听学长他们说的&#xff0c;如今已经是24年了&#xff0c;虽然只学习了一年的编程但我已经了解到了这条路上的不易。希望能够在这条路上面一路坚持下去&#xff0…

力扣_斐波那契数列

本题目本质和爬楼梯是一样的&#xff0c;主要运用的是递归来解题。 class Solution:my_dict {}def fib(self, n: int) -> int:if self.my_dict.get(n) is not None: # 先判断有没有计算过这个值return self.my_dict.get(n)tempResult 0if n > 2:tempResult self.fib…

075_基于springboot的万里学院摄影社团管理系统

目录 系统展示 开发背景 代码实现 项目案例 获取源码 博主介绍&#xff1a;CodeMentor毕业设计领航者、全网关注者30W群落&#xff0c;InfoQ特邀专栏作家、技术博客领航者、InfoQ新星培育计划导师、Web开发领域杰出贡献者&#xff0c;博客领航之星、开发者头条/腾讯云/AW…

MySql中使用findInSet和collection实践

FIND_IN_SET 需求如下&#xff1a;有张用户表&#xff0c;表里有个字段叫school&#xff0c;意为这个用户上过哪些学校&#xff0c;数据库里存的就是字符串类型&#xff0c;存的值类似"2,5,12"&#xff0c;要求就是查询出上过id为2的学校有哪些用户 解决方法&#x…

【JAVA毕设】基于JAVA的酒店管理系统

一、项目介绍 本系统前端框架采用了比较流行的渐进式JavaScript框架Vue.js。使用Vue-Router实现动态路由&#xff0c;Ajax实现前后端通信&#xff0c;Element-plus组件库使页面快速成型。后端部分&#xff1a;采用SpringBoot作为开发框架&#xff0c;同时集成MyBatis、Redis、…

qt生成uuid,转成int。ai回答亲测可以

// 生成一个随机的UUID QUuid uuid QUuid::createUuid(); // 将UUID转换为字符串 QString uuidStr uuid.toString(QUuid::WithoutBraces);// 计算MD5哈希值 QByteArray hash QCryptographicHash::hash(uuidStr.toUtf8(), QCryptographicHash::Md5);// 提取前8个字节并转换为…

云曦10月13日awd复现

一、防御 1、改用户密码 passwd <user> 2、改数据库密码 进入数据库 mysql -uroot -proot 改密码 update mysql.user set passwordpassword(新密码) where userroot; 查看用户信息密码 select host,user,password from mysql.user; 改配置文件&#xff0c;将密码改为自己…

电脑技巧:Rufus——最佳USB启动盘制作工具指南

目录 一、功能强大&#xff0c;兼容性广泛 二、界面友好&#xff0c;操作简便 三、快速高效&#xff0c;高度可定制 四、安全可靠&#xff0c;社区活跃 在日常的电脑使用中&#xff0c;无论是为了安装操作系统、修复系统故障还是进行其他需要可引导媒体的任务&#xff0c;拥…

使用 Python结合随机User-Agent与代理池进行网络请求

1. 引言 在爬虫开发过程中&#xff0c;为了模拟真实的用户行为&#xff0c;避免被目标网站识别并封锁&#xff0c;通常需要使用随机的User-Agent以及代理IP来发送网络请求。本文将介绍如何通过Python实现这一功能&#xff0c;包括设置随机User-Agent、读取代理列表&#xff0c…

web网页

HTML代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>wyy</title><!-- 引…

VSCODE c++不能自动补全的问题

最近安装了vscode&#xff0c;配置了C/C扩展&#xff0c;也按照网上说的配置了头文件路径 我发现有部分头文件是没办法解析的&#xff0c;只要包含这些头文件中的一个或者多个&#xff0c;就没有代码高亮和代码自动补全了&#xff0c;确定路径配置是没问题的&#xff0c;因为鼠…

Linux笔记之文件查找和搜索命令which,find,locate,whereis总结

Linux笔记之文件查找和搜索命令which,find,locate,whereis总结 code review! 文章目录 Linux笔记之文件查找和搜索命令which,find,locate,whereis总结1.对比2.whereis 和 which 命令区别3.locate 和 find 命令区别 1.对比 命令功能说明备注which常用于查找可直接执行的命令。…

基于ssm的萌宠商城管理系统【附源码】

基于ssm的萌宠宜家商城系统&#xff08;源码L文说明文档&#xff09; 目录 4 系统设计 4.1 系统概述 4.2 系统概要设计 4.3 系统功能结构设计 4.4 数据库设计 4.4.1 数据库E-R图设计 4.4.2 数据库表结构设计 5 系统实现 5.1 管理员功能介绍 …

【C++中的lambda表达式】

不需要借口&#xff0c;爱淡了就放手....................................................................................................... 文章目录 前言 一、【lambda表达式介绍】 1、【lamda表达式的概念】 2、【lamda表达式的语法】 二、【lambda表达式的使用】…

CAS简介

#1024程序员节&#xff5c;征文# CAS是什么&#xff1f; CAS&#xff08;Compare And Swap&#xff09;&#xff0c;即比较与交换&#xff0c;是一种乐观锁的实现方式&#xff0c;用于在不使用锁的情况下实现多线程之间的变量同步。 CAS操作包含三个操作数&#xff1a;内存位…

Stability.AI 发布 SD3.5 模型,能否逆袭击败 FLUX?如何在ComfyUI中的使用SD3.5?

就在前天&#xff0c;Stability AI 正式发布了 Stable Diffusion 3.5版本&#xff0c;包括 3 款强大的模型&#xff1a; Stable Diffusion 3.5 Large&#xff1a;拥有 80 亿参数&#xff0c;提供卓越的图像质量和精确的提示词响应&#xff0c;非常适合在 1 兆像素分辨率下的专…

鸿蒙开发:走进stateStyles多态样式

前言 一个组件&#xff0c;多种状态下&#xff0c;我们如何实现呢&#xff1f;举一个很简单的案例&#xff0c;一个按钮&#xff0c;默认状态下是黑色背景&#xff0c;点击后是红色&#xff0c;手指放开后还原黑色。 我们自然而然的就会想到利用手势的按下和抬起&#xff0c;…

美课+, 一个公司老项目,一段程序猿的技术回忆

前言 "美课"项目从2018年3月26号开始启动到2018年6月8号结束,总计两个月多的时间,项目的时间节点比较紧张.虽然最后没有上线很遗憾,但是,不管是在流程和项目上,对自己都是一次不错的尝试.下面我就对这次项目做一下iOS端的整体总结. #### 技术难点 *** 在iOS端,我感到…

鸿蒙应用开发:数据持久化

最近在搞公司项目用到了鸿蒙端的数据持久化&#xff0c;特来跟大家分享一下。 在鸿蒙开发中&#xff0c;可以使用以下几个包来实现数据的持久化处理&#xff1a; Data Ability 通过数据能力组件&#xff0c;开发者可以实现复杂的数据操作&#xff0c;包括增、删、改、查等功…