溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Vuex中使用Store

發布時間:2021-01-06 16:58:34 來源:億速云 閱讀:267 作者: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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女