Actions | Vuex

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?