vuex 设计思路和实现方式

Lillian ·
更新时间:2024-09-20
· 19 次阅读

目录

vuex 设计思路和实现

vuex 设计思路

vue 响应式设计,依赖监听、依赖收集

vuex 设计思路和实现

API概念的东西就不介绍了, 如果还不了解vuex 的应用, 可以去查看官方vuex文档 。

下面着重讲解 vuex的原理以及实现

vuex 设计思路

vuex是使用插件机制开发的, vuex 中的 store 本质就是没有template的隐藏着的vue实例

在beforeCreate 混入vuexInit ,vuexInit方法实现了store注入vue组件实例,并注册了vuex store的引用属性·$store

vuex 设计思路源码

// vuex插件公开的install方法 function install (_Vue) { if (Vue && _Vue === Vue) { { console.error( '[vuex] already installed. Vue.use(Vuex) should be called only once.' ); } return } Vue = _Vue; applyMixin(Vue); } /* ... */ var index_cjs = { Store: Store, install: install, // 开放出去install方法, 直接在项目中使用这个插件 version: '3.4.0', mapState: mapState, mapMutations: mapMutations, mapGetters: mapGetters, mapActions: mapActions, createNamespacedHelpers: createNamespacedHelpers }; return index_cjs; // 混入到项目中 function applyMixin (Vue) { var version = Number(Vue.version.split('.')[0]); if (version >= 2) { Vue.mixin({ beforeCreate: vuexInit }); // 在生命周期beforeCreate创建全局混入函数 } else { // 覆盖初始化并注入vuex初始化过程 // 1.x 以上版本兼容。 var _init = Vue.prototype._init; Vue.prototype._init = function (options) { if ( options === void 0 ) options = {}; options.init = options.init ? [vuexInit].concat(options.init) : vuexInit; _init.call(this, options); }; } function vuexInit () { // Vuex 初始化钩子,注入到每个实例初始化钩子列表中 var options = this.$options; // store injection if (options.store) { this.$store = typeof options.store === 'function' ? options.store() : options.store; } else if (options.parent && options.parent.$store) { this.$store = options.parent.$store; } } } // 使用Vue实例来存储状态树 // 隐藏警告,以防用户添加了, 一些优先的 global mixins function resetStoreVM (store, state, hot) { /* other... */ var silent = Vue.config.silent; Vue.config.silent = true; store._vm = new Vue({ // 创建一个vue 实例 data: { $$state: state }, computed: computed }); Vue.config.silent = silent; /* other... */ } vue 响应式设计,依赖监听、依赖收集

想深刻理解 vuex 的设计思路。

要明白 vue 对象数据 Object.defineProperty ,getter/setter 方法的代理劫持的原理

// src/core/instance/state.js // 初始化组件的state export function initState (vm: Component) { vm._watchers = [] const opts = vm.$options if (opts.props) initProps(vm, opts.props) if (opts.methods) initMethods(vm, opts.methods) // 当组件存在data属性 if (opts.data) { initData(vm) } else { observe(vm._data = {}, true /* asRootData */) } // 当组件存在 computed属性 if (opts.computed) initComputed(vm, opts.computed) if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch) } }

vuex 就是实现了带有计算属性的 data 数据, 原理和 initComputed、 initData 是一致的

如果上面已经完全理解,想更深度了解响应式依赖 继续阅读vue的computed、vm.$data原理

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。 



设计思路 vuex

需要 登录 后方可回复, 如果你还没有账号请 注册新账号