欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vuex之理解Store的用法

程序员文章站 2023-09-07 20:37:51
1.什么是store? 说了,vuex就是提供一个仓库,store仓库里面放了很多对象。其中state就是数据源存放地,对应于与一般vue对象里面的data(后面讲到...

1.什么是store?

说了,vuex就是提供一个仓库,store仓库里面放了很多对象。其中state就是数据源存放地,对应于与一般vue对象里面的data(后面讲到的actionsmutations对应于methods)。

在使用vuex的时候通常会创建store实例new vuex.store({state,getters,mutations,actions})有很多子模块的时候还会使用到modules

Vuex之理解Store的用法

总结,store类就是存储数据和管理数据方法的仓库,实现方式是将数据和方法已对象形式传入其实例中。要注意一个应用或是项目中只能存在一个store实例!!

2.store源码分析

class store{
  constructor (options = {}) {
  // 1.部分2个‘断言函数'判断条件
  assert(vue, `must call vue.use(vuex) before creating a store 
  instance.`) // 在store实例化之前一定要确保vue的存在
  assert(typeof promise !== 'undefined', `vuex requires a promise polyfill in this browser.`)
  //确保promise存在
  
  // 2.结构赋值拿到options里面的state,plugins和strict
  const {
  state = {}, //rootstate
  plugins = [], // 插件
  strict = false //是否严格模式
   } = options
   
  // 3.store internal state创建store内部属性
  this._options = options //存储参数
  this._committing = false //标识提交状态,保证修改state只能在mutation里面,不能在外部随意修改
  this._actions = object.create(null) //存储用户定义的actions
  this._mutations = object.create(null) //存储用户定义的mutations
  this._wrappedgetters = object.create(null) //存储用户定义的getters
  this._runtimemodules = object.create(null) //存储运行时的modules
  this._subscribers = [] //存储所有堵mutation变化的订阅者
  this._watchervm = new vue() //借用vue实例的方法,$watch来观测变化
  
  // 4.将dispatch和commit的this指向当前store实例
  const store = this
  const { dispatch, commit } = this
  this.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)}}

逐步分析每一个模块。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。