Actions | Vuex
文章推薦指數: 80 %
store.dispatch('xxx') , or use the mapActions helper which maps component methods to store.dispatch calls (requires root store injection):. GuideAPIReferenceReleaseNotesv4.xv3.xLanguagesEnglish简体中文日本語PortuguêsGitHubIntroductionWhatisVuex?InstallationGettingStartedCoreConceptsStateGettersMutationsActionsDispatchingActionsDispatchingActionsinComponentsComposingActionsModulesAdvancedApplicationStructureCompositionAPIPluginsStrictModeFormHandlingTestingHotReloadingTypeScriptSupportMigrationGuideMigratingto4.0from3.xActions#TrythislessononScrimbaActionsaresimilartomutations,thedifferencesbeingthat:Insteadofmutatingthestate,actionscommitmutations.Actionscancontainarbitraryasynchronousoperations.Let'sregisterasimpleaction:conststore=createStore({ state:{ count:0 }, mutations:{ increment(state){ state.count++ } }, actions:{ increment(context){ context.commit('increment') } } }) Actionhandlersreceiveacontextobjectwhichexposesthesamesetofmethods/propertiesonthestoreinstance,soyoucancallcontext.committocommitamutation,oraccessthestateandgettersviacontext.stateandcontext.getters.Wecanevencallotheractionswithcontext.dispatch.WewillseewhythiscontextobjectisnotthestoreinstanceitselfwhenweintroduceModuleslater.Inpractice,weoftenuseES2015argumentdestructuringtosimplifythecodeabit(especiallywhenweneedtocallcommitmultipletimes):actions:{ increment({commit}){ commit('increment') } } DispatchingActions#Actionsaretriggeredwiththestore.dispatchmethod:store.dispatch('increment') Thismaylooksillyatfirstsight:ifwewanttoincrementthecount,whydon'twejustcallstore.commit('increment')directly?Rememberthatmutationshavetobesynchronous.Actionsdon't.Wecanperformasynchronousoperationsinsideanaction:actions:{ incrementAsync({commit}){ setTimeout(()=>{ commit('increment') },1000) } } Actionssupportthesamepayloadformatandobject-styledispatch://dispatchwithapayload store.dispatch('incrementAsync',{ amount:10 }) //dispatchwithanobject store.dispatch({ type:'incrementAsync', amount:10 }) Amorepracticalexampleofreal-worldactionswouldbeanactiontocheckoutashoppingcart,whichinvolvescallinganasyncAPIandcommittingmultiplemutations:actions:{ checkout({commit,state},products){ //savetheitemscurrentlyinthecart constsavedCartItems=[...state.cart.added] //sendoutcheckoutrequest,andoptimistically //clearthecart commit(types.CHECKOUT_REQUEST) //theshopAPIacceptsasuccesscallbackandafailurecallback shop.buyProducts( products, //handlesuccess ()=>commit(types.CHECKOUT_SUCCESS), //handlefailure ()=>commit(types.CHECKOUT_FAILURE,savedCartItems) ) } } Noteweareperformingaflowofasynchronousoperations,andrecordingthesideeffects(statemutations)oftheactionbycommittingthem.DispatchingActionsinComponents#Youcandispatchactionsincomponentswiththis.$store.dispatch('xxx'),orusethemapActionshelperwhichmapscomponentmethodstostore.dispatchcalls(requiresrootstoreinjection):import{mapActions}from'vuex' exportdefault{ //... methods:{ ...mapActions([ 'increment',//map`this.increment()`to`this.$store.dispatch('increment')` //`mapActions`alsosupportspayloads: 'incrementBy'//map`this.incrementBy(amount)`to`this.$store.dispatch('incrementBy',amount)` ]), ...mapActions({ add:'increment'//map`this.add()`to`this.$store.dispatch('increment')` }) } } ComposingActions#Actionsareoftenasynchronous,sohowdoweknowwhenanactionisdone?Andmoreimportantly,howcanwecomposemultipleactionstogethertohandlemorecomplexasyncflows?Thefirstthingtoknowisthatstore.dispatchcanhandlePromisereturnedbythetriggeredactionhandleranditalsoreturnsPromise:actions:{ actionA({commit}){ returnnewPromise((resolve,reject)=>{ setTimeout(()=>{ commit('someMutation') resolve() },1000) }) } } Nowyoucando:store.dispatch('actionA').then(()=>{ //... }) Andalsoinanotheraction:actions:{ //... actionB({dispatch,commit}){ returndispatch('actionA').then(()=>{ commit('someOtherMutation') }) } } Finally,ifwemakeuseofasync/await,wecancomposeouractionslikethis://assuming`getData()`and`getOtherData()`returnPromises actions:{ asyncactionA({commit}){ commit('gotData',awaitgetData()) }, asyncactionB({dispatch,commit}){ awaitdispatch('actionA')//waitfor`actionA`tofinish commit('gotOtherData',awaitgetOtherData()) } } It'spossibleforastore.dispatchtotriggermultipleactionhandlersindifferentmodules.InsuchacasethereturnedvaluewillbeaPromisethatresolveswhenalltriggeredhandlershavebeenresolved.MutationsModules
延伸文章資訊
- 1About us - MapAction
- 2vuex:弄懂mapState、mapGetters、mapMutations - 知乎专栏
vuex:弄懂mapState、mapGetters、mapMutations、mapActions. 2 年前· 来自专栏全栈前端. vuex进阶. 一、state. 1.1 引入vuex ...
- 3Action | Vuex
store.dispatch('xxx') 分发action,或者使用 mapActions 辅助函数将组件的methods 映射为 store.dispatch 调用(需要先在根节点注入 st...
- 4[Vue.js] Vuex 學習筆記(8) - actions 的核心概念
store.dispatch('xxx') 分發action,或者使用 mapActions 輔助函數將組件的methods 映射為 store.dispatch 調用。 import { ma...
- 5Vuex showdown: Mutations vs. actions - LogRocket Blog