µ±Ç°Î»Öà Ö÷Ò³ > ÍøÕ¾¼¼Êõ > ´úÂëÀà >

    dz̸vuexΪʲô²»½¨ÒéÔÚactionÖÐÐÞ¸Ästate

    À¸Ä¿£º´úÂëÀà ʱ¼ä£º2020-02-02 15:11

    ±³¾°

    ÔÚ×î½üµÄÒ»´ÎÐèÇ󿪷¢¹ý³ÌÖУ¬ÓÐÔÙ´ÎʹÓõ½Vuex£¬ÔÚ״̬¸üÐÂÕâÒ»·½Ã棬ÎÒʼÖÕ×ñÑ­×Źٷ½µÄ¡°¶£Öö¡±£¬½÷¼Ç¡°Ò»¶¨²»ÒªÔÚactionÖÐÐÞ¸Ästate£¬¶øÊÇÒªÔÚmutationÖÐÐ޸ġ±£»ÓÚÊÇÎÒ²»½û²úÉúÁËÒ»¸öÒÉÎÊ£ºVuexΪʲôҪ¸ø³öÕâ¸öÏÞÖÆ£¬ËüÊÇ»ùÓÚʲôԭÒòÄØ£¿´ø×ÅÕâ¸öÒÉÎÊÎҲ鿴VuexµÄÔ´Â룬ÏÂÃæÇë´ó¼Ò¸ú×ÅÎҵĽŲ½£¬À´Ò»Æð½Ò¿ªÕâ¸öÎÊÌâµÄÃæÉ´¡£

    Ò»ÆðÔĶÁÔ´Âë°É~

    1.Ê×ÏÈÎÒÃÇ¿ÉÒÔÔÚsrc/store.jsÕâ¸öÎļþµÄStoreÀàÖÐÕÒµ½ÏÂÃæÕâ¶Î´úÂë

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

    ÉÏÃæÊÇVuexÁ½¸ö×îºËÐĵÄAPI£ºdispatch & commit£¬ËüÃÇÊÇ·Ö±ðÓÃÀ´Ìá½»actionºÍmutationµÄ

    ÄÇô¼ÈÈ»ÎÒÃǽñÌìµÄÄ¿µÄÊÇΪÁË¡°Á˽âΪʲô²»ÄÜÔÚactionÖÐÐÞ¸Ästate¡±£¬ËùÒÔÎÒÃǾÍÏÈ¿´¿´mutationÊÇÔõÑùÐÞ¸ÄstateµÄ£¬È»¶ømutationÊÇͨ¹ýcommitÌá½»µÄ£¬ËùÒÔÎÒÃÇÏÈ¿´Ò»ÏÂcommitµÄÄÚ²¿ÊµÏÖ

    commit&mutation

    2.commit·½·¨µÄºËÐÄ´úÂë´óÖÂÈçÏ£º

    commit (_type, _payload, _options) {
      // ...
      this._withCommit(() => {
       entry.forEach(function commitIterator (handler) {
        handler(payload)
       })
      })
      // ...
    }
    

    ²»ÄÑ¿´³ö£¬VuexÔÚcommit£¨Ìá½»£©Ä³ÖÖÀàÐ͵Ämutationʱ£¬»áÏÈÓÃ_withCommit°ü¹üÒ»ÏÂÕâЩmutation£¬¼´×÷Ϊ²ÎÊý´«Èë_withCommit£»ÄÇôÎÒÃÇÀ´¿´¿´_withCommitµÄÄÚ²¿ÊµÏÖ£¨ps£ºÕâÀïÖ®ËùÒÔ˵¡±Ä³ÖÖÀàÐ͵Ämutation¡°£¬ÊÇÒòΪVuexµÄÈ·Ö§³ÖÉùÃ÷¶à¸öͬÃûµÄmutation£¬²»¹ýÇ°ÌáÊÇËüÃÇÔÚ²»Í¬µÄnamespaceÏ£»actionͬÀí£©

    3._withCommit·½·¨µÄ´úÂëÈçÏ£º

    _withCommit (fn) {
      const committing = this._committing
      this._committing = true
      fn()
      this._committing = committing
     }
    

    Êǵģ¬ÄãûÓп´´í£¬ËüÕæµÄÖ»ÓÐ4ÐдúÂ룻ÕâÀïÎÒÃÇ×¢Òâµ½ÓÐÒ»¸ö±ê־λ_committing£¬ÔÚÖ´ÐÐfnÇ°£¬Õâ¸ö±ê־λ»á±»ÖÃΪtrue£¬Õâ¸öµãÎÒÃÇÏȼÇÏ£¬Ò»»á¶ù»áÓõ½

    4.½ÓÏÂÀ´£¬ÎÒҪΪ´ó¼ÒÒª½éÉܵÄÊÇresetStoreVMÕâ¸öº¯Êý£¬ËüµÄ×÷ÓÃÊdzõʼ»¯store£¬ËüÊ״α»Ö´ÐÐÊÇÔÚStoreµÄ¹¹Ô캯ÊýÖÐ

    function resetStoreVM (store, state, hot) {
     // ...
     if (store.strict) {
      enableStrictMode(store)
     }
    // ...
    }
    

    ÔÚÕâÀïÓÐÒ»´¦ÐèÒªÎÒÃÇ×¢Ò⣺resetStoreVM¶Ôstrict£¨ÊÇ·ñÆôÓÃÑϸñģʽ£©×öÁËÅжϣ¬ÕâÀï¼ÙÉèÎÒÃÇÆôÓÃÑϸñģʽ£¬ÄÇô¾Í»áÖ´ÐÐenableStrictModeÕâ¸öº¯Êý£¬ÏÂÃæ¼ÌÐøÀ´¿´¿´ËüµÄÄÚ²¿ÊµÏÖ

    function enableStrictMode (store) {
     store._vm.$watch(function () { return this._data.$$state }, () => {
      if (process.env.NODE_ENV !== 'production') {
       assert(store._committing, `do not mutate vuex store state outside mutation handlers.`)
      }
     }, { deep: true, sync: true })
    }
    

    ÕâÀï¶ÔVue×é¼þʵÀýµÄstate×öÁ˼àÌý£¬Ò»µ©¼àÌýµ½±ä»¯£¬¾Í»áÖ´ÐÐasset£¨¶ÏÑÔ£©£¬Ëü¶ÏÑÔµÄÇ¡ÇɾÍÊǸղÅÎÒÈôó¼Ò¼ÇסµÄÄǸö_committing±ê־룬ÄÇôÎÒÃÇÔÙÀ´¿´¿´Õâ¸öasset×öÁËЩʲô

    5.asset·½·¨ÔÚsrc/util.jsÕâ¸öÎļþÖÐ

    export function assert (condition, msg) {
     if (!condition) throw new Error(`[vuex] ${msg}`)
    }