Vuex 4源码学习笔记 - Store 构造函数都干了什么(四)

本文深入探讨Vuex的Store构造函数,解析如何通过`createStore`创建实例,并结合`installModule`初始化模块及`resetStoreState`实现响应式状态管理。文中详细阐述了Store构造函数内部的module注册、状态响应式化以及插件应用的过程,为理解Vuex工作原理提供了关键信息。
摘要由CSDN通过智能技术生成

在上一篇笔记中:Vuex 4源码学习笔记 - Vuex是怎么与Vue结合?(三)

我们复习了Vuex的使用方式,以及为什么要使用Vuex,同时看到了Vuex是如何与Vue去结合到一起的。

Vuex是通过Vue插件的方式,通过use函数将Vuex实例对象绑定到Vue中。

然后我们在页面或者组件中可以通过useStore函数或者this.$store两种方式在页面中访问到store实例。

首先创建Vuex实例的方式为调用createStore函数来调用

import {
    createStore } from 'vuex'

export default createStore({
   
  state: {
    /**...**/ },
  getters: {
    /**...**/ },
  actions: {
    /**...**/ },
  mutations: {
    /**...**/ }
})

createStore函数的源代码,可以看到实际是new了一个Store类的对象

export function createStore (options) {
   
  return new Store(options)
}

Store 构造函数

然后我们看到Store类的源代码,new的第一步首先就是调用constructor构造函数

export class Store {
   
  constructor (options = {
    }) {
   
    if (__DEV__) {
   
      assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)
      assert(this instanceof Store, `store must be called with the new operator.`)
    }

    const {
   
      /* 一个数组,包含应用在 store 上的插件方法。*/
      plugins = [],
      /* 使 Vuex store 进入严格模式,在严格模式下,任何 mutation 处理函数以外修改 Vuex state 都会抛出错误。*/
      strict = false,
      /* devtool插件状态*/
      devtools
    } = options

    // store internal state -> store的内部状态
    /* 用来判断严格模式下是否是用mutation修改state的 */
    this._committing = false
    /* 存放action */
    this._actions = Object.create(null)
    /* 存放action订阅器*/
    this._actionSubscribers = []
    /* 存放mutation */
    this._mutations = Object.create(null)
    /* 存放getter */
    this._wrappedGetters = Object.create(null)
    /* module收集器 */
    this._modules = new ModuleCollection(options)
    /* 根据namespace存放module */
    this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值