温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Vuex中使用Store

发布时间:2021-01-06 16:58:34 来源:亿速云 阅读:231 作者:Leah 栏目:web开发

如何在Vuex中使用Store?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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)}}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI