Vue组件通信原理剖析(二)全局状态管理Vuex

首先我们先从一个面试题入手。

面试官问: “Vue中组件通信的常用方式有哪些?”
我答:
1. props
2. 自定义事件
3. eventbus
4. vuex
5. 还有常见的边界情况$parent、$children、$root、$refs、provide/inject
6. 此外还有一些非props特性$attrs、$listeners

面试官追问:“那你能分别说说他们的原理吗?”
我:[一脸懵逼]😳

今天我们来看看Vuex内部的奥秘!
如果要看别的属性原理请移步到Vue组件通信原理剖析(一)事件总线的基石 on和on和onemit和Vue组件通信原理剖析(三)provide/inject原理分析

vuex

Vuex集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以可预测的方式发生变化。
在这里插入图片描述

我们先看看如何使用vuex,

  • 第一步:定义一个Store

    // store/index.js
    import Vue from 'vue'
    import Vuex from 'vuex'Vue.use(Vuex)export default = new Vuex.Store({state: {counter: 0},getters: {doubleCounter(state) {return state.counter * 2}},mutations: {add(state) {state.counter ++ }},actions: {add({commit}) {setTimeout(() => {commit('add')}, 1000);}}
    })
    
  • 第二步,挂载app

    // main.js
    import vue from 'vue'
    import App form './App.vue'
    import store from './store'new Vue({store,render: h => h(App)
    }).$mount('#app')
    
  • 第三步:状态调用

    // test.vue
    <p @click="$store.commit('add')">counter: {{ $store.state.counter }}</p>
    <p @click="$store.dispatch('add')">async counter: {{ $store.state.counter }}</p>
    <p>double counter: {{ $store.getters.doubleCounter }}</p>
    

从上面的例子,我们可以看出,vuex需要具备这么几个特点:

  1. 使用Vuex只需执行 Vue.use(Vuex),保证vuex是以插件的形式被vue加载。
  2. state的数据具有响应式,A组件中修改了,B组件中可用修改后的值。
  3. getters可以对state的数据做动态派生。
  4. mutations中的方法是同步修改。
  5. actions中的方法是异步修改。

那我们今天就去源码里探索以下,vuex是怎么实现的,又是怎么解决以上的问题的!

问题1:vuex的插件加载机制

所谓插件机制,就是需要实现Install方法,并且通过mixin形式混入到Vue的生命周期中,我们先来看看Vuex的定义

  • 需要对外暴露一个对象,这样就可以满足new Vuex.Store()

    // src/index.js  
    import { Store, install } from './store'
    import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from './helpers'export default {Store,install,version: '__VERSION__',mapState,mapMutations,mapGetters,mapActions,createNamespacedHelpers
    }
    
  • 其次是定义store,并且实现vue的Install方法

    // src/store.js
    let Vue // bind on installexport class Store {......
    }// 实现的Install方法 
    export function install (_Vue) {if (Vue && _Vue === Vue) {if (process.env.NODE_ENV !== 'production') {console.error('[vuex] already installed. Vue.use(Vuex) should be called only once.')}return}Vue = _VueapplyMixin(Vue)
    }
    

问题2:state的数据响应式

看懂了Vuex的入口定义,下面我们就针对store的定义来一探究竟,先看看state的实现

// src/store.js
export class Store {constructor(options = {}) {......// strict modethis.strict = strictconst state = this._modules.root.state// initialize the store vm, which is responsible for the reactivity// (also registers _wrappedGetters as computed properties)// 看上面的注释可以得知,resetStoreVM就是初始化store中负责响应式的vm的方法,而且还注册所有的gettersz作为vm的计算属性resetStoreVM(this, state)}
}

我们来看看resetStoreVM的具体实现

// src/store.js
function resetStoreVM (store, state, hot) {const oldVm = store._vm// bind store public gettersstore.getters = {}// reset local getters cachestore._makeLocalGettersCache = Object.create(null)const wrappedGetters = store._wrappedGettersconst computed = {}// 这里是实现getters的派生forEachValue(wrappedGetters, (fn, key) => {// use computed to leverage its lazy-caching mechanism// direct inline function use will lead to closure preserving oldVm.// using partial to return function with only arguments preserved in closure environment.computed[key] = partial(fn, store)Object.defineProperty(store.getters, key, {get: () => store._vm[key],enumerable: true // for local getters})})// use a Vue instance to store the state tree// suppress warnings just in case the user has added// some funky global mixins// 这是是通过new一个Vue实例,并将state作为实例的datas属性,那他自然而然就具有了响应式const silent = Vue.config.silentVue.config.silent = truestore._vm = new Vue({data: {$$state: state},computed})Vue.config.silent = silent// enable strict mode for new vmif (store.strict) {enableStrictMode(store)}if (oldVm) {if (hot) {// dispatch changes in all subscribed watchers// to force getter re-evaluation for hot reloading.store._withCommit(() => {oldVm._data.$$state = null})}Vue.nextTick(() => oldVm.$destroy())}
}

问题3:getters实现state中的数据的派生

关于getters的实现,我们在上面也做了相应的解释,实际上就是将getters的方法包装一层后,收集到computed对象中,并使用Object.defineProperty注册store.getters,使得每次取值时,从store._vm中取。

关键的步骤就是创建一个Vue的实例

store._vm = new Vue({data: {$$state: state // 这是store中的所有state},computed // 这是store中的所有getters
})

问题4:mutations中同步commit

// src/store.js
// store的构造函数
constructor(options = {}) {// 首先在构造方法中,把store中的commit和dispatch绑定到自己的实例上,// 为什么要这么做呢?// 是因为在commit或者dispatch时,尤其是dispatch,执行function时会调用实例this,而方法体内的this是具有作用域属性的,所以如果要保证每次this都代表store实例,就需要重新绑定一下。const store = thisconst { dispatch, commit } = thisthis.dispatch = function boundDispatch (type, payload) {return dispatch.call(store, type, payload)}this.commit = function boundCommit (type, payload, options) {return commit.call(store, type, payload, options)}
}// commit 的实现
commit (_type, _payload, _options) {// check object-style commitconst {type,payload,options} = unifyObjectStyle(_type, _payload, _options)const mutation = { type, payload }// 通过传入的类型,查找到mutations中的对应的入口函数const entry = this._mutations[type]......// 这里是执行的主方法,通过遍历入口函数,并传参执行this._withCommit(() => {entry.forEach(function commitIterator (handler) {handler(payload)})})......
}

问题5:actions中的异步dispatch

上面说了在构造store时绑定dispatch的原因,下面我们就继续看看dispatch的具体实现。

// src/store.js
// dispatch 的实现
dispatch (_type, _payload) {// check object-style dispatchconst {type,payload} = unifyObjectStyle(_type, _payload)const action = { type, payload }// 同样的道理,通过type获取actions中的入口函数const entry = this._actions[type]······// 由于action是异步函数的集合,这里就用到了Promise.all,来合并多个promise方法并执行const result = entry.length > 1? Promise.all(entry.map(handler => handler(payload))): entry[0](payload)return result.then(res => {try {this._actionSubscribers.filter(sub => sub.after).forEach(sub => sub.after(action, this.state))} catch (e) {if (process.env.NODE_ENV !== 'production') {console.warn(`[vuex] error in after action subscribers: `)console.error(e)}}return res})
}

到这里,我们就把整个store中状态存储和状态变更的流程系统的串联了一遍,让我们对Vuex内部的机智有个简单的认识,最后我们根据我们对Vuex的理解来实现一个简单的Vuex。

// store.js
let Vue// 定义store类
class Store{constructor(options = {}) {this.$options = optionsthis._mutations = options.mutationsthis._actions = options.actionsthis._wrappedGetters = options.getters// 定义computedconst computed = {}this.getters = {}const store = thisObject.keys(this._wrappedGetters).forEach(key => {// 获取用户定义的gettersconst fn = store._wrappedGetters[key]// 转换为computed可以使用无参数形式computed[key] = function() {return fn(store.state)}// 为getters定义只读属性Object.defineProperty(store.getters, key {get:() => store._vm[key]})})// state的响应式实现this._vm = new Vue({data: {// 加两个$,Vue不做代理$$state: options.state},computed // 添加计算属性})this.commit = this.commit.bind(this)this.dispatch = this.dispatch.bind(this)}// 存取器,获取store.state ,只通过get形式获取,而不是直接this.xxx, 达到对stateget state() {return this._vm._data.$$state}set state(v) {// 如果用户不通过commit方式来改变state,就可以在这里做一控制}// commit的实现commit(type, payload) {const entry = this._mutations[type]if (entry) {entry(this.state, payload)}}// dispatch的实现dispatch(type, payload) {const entry = this._actions[type]if (entry) {entry(this, payload)}}  
}// 实现install
function install(_Vue) {Vue = _VueVue.mixin({beforeCreate() {if (this.$options.store) {Vue.prototype.$Store = this.$options.store // 这样就可以使用 this.$store}}})
}// 导出Vuex对象
export default {Store,install
}

全部文章链接

Vue组件通信原理剖析(一)事件总线的基石 on和on和onemit
Vue组件通信原理剖析(二)全局状态管理Vuex
Vue组件通信原理剖析(三)provide/inject原理分析

最后喜欢我的小伙伴也可以通过关注公众号“剑指大前端”,或者扫描下方二维码联系到我,进行经验交流和分享,同时我也会定期分享一些大前端干货,让我们的开发从此不迷路。
在这里插入图片描述

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

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

相关文章

初识单点登录及JWT实现

单点登录 多系统&#xff0c;单一位置登录&#xff0c;实现多系统同时登录的一种技术 &#xff08;三方登录&#xff1a;某系统使用其他系统的用户&#xff0c;实现本系统登录的方式。如微信登录、支付宝登录&#xff09; 单点登录一般是用于互相授信的系统&#xff0c;实现单一…

Vue组件通信原理剖析(三)provide/inject原理分析

首先我们先从一个面试题入手。 面试官问&#xff1a; “Vue中组件通信的常用方式有哪些&#xff1f;” 我答&#xff1a; 1. props 2. 自定义事件 3. eventbus 4. vuex 5. 还有常见的边界情况$parent、$children、$root、$refs、provide/inject 6. 此外还有一些非props特性$att…

iMX6开发板-uboot-网络设置和测试

本文章基于迅为IMX6开发板 将iMX6开发板通过网线连接到路由器&#xff0c;同时连接好调试串口&#xff0c;上电立即按 enter&#xff0c;即可进入 uboot。然后输入命令 pri&#xff0c;查看开发板当前的配置&#xff0c;如下图所示可以看到 ip 地址、子网掩码 等信息。 本文档测…

Django ajax 检测用户名是否已被注册

添加一个 register.html 页面 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title> </head> <body> <form><p>用户名<input id"username" type&…

pyqt5控件

背景色设置 self.tab.setStyleSheet("background: rgb(238, 233, 233)") self.but_0.setStyleSheet("background: rgb(0, 255, 255)")样式&#xff1a; self.but_0.setStyle(QStyleFactory.create("Windows"))字体&#xff1a; self.lineEdit.se…

详解JDBC连接数据库

一、概念 1. 为了能让程序操作数据库&#xff0c;对数据库中的表进行操作&#xff0c;每一种数据库都会提供一套连接和操作该数据库的驱动&#xff0c;而且每种数据库的驱动都各不相同&#xff0c;例如mysql数据库使用mysql驱动&#xff0c;oracle数据库使用oracle驱动&#xf…

ASP.NET MVC 自定义模型绑定1 - 自动把以英文逗号分隔的 ID 字符串绑定成 Listint...

直接贴代码了&#xff1a; CommaSeparatedModelBinder.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc;namespace MvcSample.Extensions {public class CommaSeparatedMode…

ZOJ4024 Peak

题意 给出一个数组 判断这个数组是否形成了一个“山峰” 即中间有个数最大 从第一个数到这个数递增 从这个数到最后一个数递减 模拟 从两端分别以递增和递减判断 看第一个不满足递增或递减的数是否相等并且没越界就可以了 AC代码&#xff1a; 1 #include<bits/stdc.h>2 u…

基本数据类型与String之间的转换

字符串转基本数据类型 调用基本数据类型对应的包装类中的方法parseXXX(String)或valueOf(String)即可返回相应基本类型。 基本数据类型转字符串 一种方法是将基本数据类型与空字符串&#xff08;""&#xff09;连接&#xff08;&#xff09;即可获得其所对应的字符串…

springmvc跨域问题

1、跨域问题&#xff1a; 按照网上所有的方法试了一遍&#xff0c;都没跨过去&#xff0c;正在无助之际&#xff0c;使用filter按照下面的方法解决的时候出现了转机&#xff1a; 添加filter&#xff1a; package com.thc.bpm.filter;import javax.servlet.*; import javax.serv…

柳传志给年轻人的建议:比起过日子,更要奔日子

改革开放的 40 年&#xff0c;是柳传志实现人生价值的 40 年。 十一届三中全会后&#xff0c;伴随“科学的春天”&#xff0c;迎着改革开放的大潮&#xff0c;柳传志“下海”了。但他并没想到&#xff0c;自己选择的电脑行业&#xff0c;让他和联想集团站在了潮头。 从 1984 年…

成功秀了一波scala spark ML逻辑斯蒂回归

1、直接上官方代码&#xff0c;调整过的&#xff0c;方可使用 package com.test import org.apache.spark.{SparkConf, SparkContext} import org.apache.spark.mllib.classification.{LogisticRegressionModel, LogisticRegressionWithLBFGS} import org.apache.spark.mllib.e…

记录一次查询log的经历

一大早发现生产数据库的基础资料被删除。 由于每天都做了差异备份&#xff0c;而且是基础资料&#xff0c;这样数据就不会担心找不回来。 首先通过每天的差异本分文件进行查看数据丢失的大概时间&#xff0c;查到数据丢失是在17晚上备份过后18丢失的。 然后找18号的数据库执行记…

移动端轮播图

1. 页面布局 1.1 页面框架 <body><div class"box"><div class"tupian"><img src"4.webp" alt""><img src"1.webp" alt""><img src"2.webp" alt""><…

Boost 序列化

原文链接&#xff1a; https://blog.csdn.net/qq2399431200/article/details/45621921 1. 编译器 gcc, boost 1.55 2.1第一个简单的例子 —— Hello World &#xff0c;将字符串内容归档到文本文件中 #include <iostream>#include <fstream>#include <string>…

docker CE 的安装

一、Docker CE的安装1.先决条件运行环境&#xff1a;Ubuntu 64位或者其他支持Docker的64位系统运行配置&#xff0c;linux内核版本必须大于 3.10&#xff0c;否则会因为缺少容器运行所需的功能而出错。 2.在ubuntu下安装Docker CEUbuntu版本 Cosmic 18.10  Bionic 18.04 (…

nodeJS中的异步编程

nodejs 不是单线程 在博客项目中关于异步问题&#xff1a; 1.当用户添加一条博客时 需要通过post方式向服务器发送数据 后台获取用户以post方式拿到传送过来的数据 然后存入数据库&#xff1a; 上面的代码&#xff1a;创建一个空字符串 当用户向服务器发送请求时出发data事件将…

day01笔记

linux基本命令的学习&#xff1a; 1.查看主机名hostname 2.修改主机名hostnamectl set-hostname s16ds 3.linux命令提示符 [roots16ds ~]# # 超级用户的身份提示符 $ 普通用户的身份提示符4.修改命令提示符 PS1变量控制 [roots16ds ~]# echo $PS1 [\u\h \W]\$PS1[\u\h \w \t]…

angular 路由

1. vscode编辑器快速新建主路由&#xff1a; ng-router注意修改为 根路由为&#xff1a;‘forRoot()’app-route.module.ts;{ path:,redirectTo:/login,pathMatch:full } 当路由为空的时候&#xff0c;会重定向到/login路由&#xff0c;必须加上pathMatch:full 1 import { Rou…

nodeJs 操作数据库

首先在node中下载mysql包 npm install mysql 连接数据库 var mysql require(mysql); var con mysql.createConnection({host : localhost,user : root,password : root,database : blog });开启链接 con.connect();执行增删改查 不同功能创建不同的sql语句即可…