
手写vuex源码
创建项目 进入项目 -چار井到项目文件夹: 安装 Vuex -使用
发布日期:2021-05-13 22:21:40
浏览次数:15
分类:精选文章
本文共 1646 字,大约阅读时间需要 5 分钟。
一、项目准备
创建一个 Vue 项目
- 使用
vue create componentName
命令创建新项目
cd componentName
vue add vuex
安装 Vuex 插件vue add vuex
2. 手写 Vuex
本 Ottaway 结构需要暴露一个包含 Store 和 install 的对象,所以我们需要自定义 Vue 插件实现手写 Vuex
// store/vuex.jsexport class Store { constructor(options) { this._mutations = options.mutations this._actions = options.actions this._wrappedGetters = options.getters this.getters = {} this._vm = new Vue({ data: { $$state: options.state } }) // 定义 computed 状态 this.computed = [] this._wrappedGetters.forEach((getter, key) => { this.computed[key] = () => { return getter(this.state) } Object.defineProperty(this.getters, key, { get: () => this._vm[key] }) }) } get state() { return this._vm.data.$$state } set state(v) { console.warn('请使用 replaceState 重置状态') } commit(type, payload) { if (this._mutations[type]) { this._mutations[type](this.state, payload) } } dispatch(type, payload) { if (this._actions[type]) { this._actions[type](this, payload) } }}export function install(Vue) { Vue.mixin({ beforeCreate() { if (this.$options.store) { Vue.prototype.$store = this.$options.store } } })}
3. 整体代码
完整的自定义 Vuex 插件代码:
// store/vuex.jsexport { Store, install } from './vuex'# App.vue 中使用 {{ $store.state.count }} async: {{ $store.state.count }} # 安装插件在 Vue 创建过程中添加插件:```bashvue add vuex
然后在 main.js 中使用自定义插件:
import { install } from '../store/vuex'new Vue({ store: new Store({ # 你的 Vuex 配置 }), install})
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月19日 00时00分12秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
js编写动态时钟
2019-03-06
JavaSE总结
2019-03-06
手动造轮子——基于.NetCore的RPC框架DotNetCoreRpc
2019-03-06
Python IO编程
2019-03-06
CSS入门总结
2019-03-06
使用 TortoiseGit 时,报 Access denied 错误
2019-03-06
基于 HTML5 WebGL 的污水处理厂泵站自控系统
2019-03-06
[系列] Go gRPC 调试工具
2019-03-06
django-表单之模型表单渲染(六)
2019-03-06
c++之程序流程控制
2019-03-06
一位年轻而优秀的.NET开发者的成长点滴
2019-03-06
如何使用ABP进行软件开发(1) 基础概览
2019-03-06
AlwaysOn配置时在连接步骤时报错(35250)
2019-03-06
排序算法之总结
2019-03-06
微软云Linux服务器 Mysql、tomcat远程连接错误解决办法
2019-03-06
Python数据分析(二): Numpy技巧 (2/4)
2019-03-06
09 . Python3之常用模块
2019-03-06
Python学习笔记-StatsModels 统计回归(3)模型数据的准备
2019-03-06
Velocity.js初步
2019-03-06