Best practices for Vuex mapping - LogRocket Blog

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

Vuex mapState; When should you map the entire Vuex state? What are Vuex mapGetters ? Vuex map mutations; Mapping Vuex actions ... Share Reply 4 MosesAnumaduFollow I'masoftwaredeveloperwithaninterestinwritingtechnicalarticlesandtutorials.Ihaveoverfouryearsofcodingexperiencewithvarioustechnologies.Ilovetoshareknowledgeintheformofwriting. BestpracticesforVuexmapping  November17,2021 3minread 1040 Editor’snote:Thispostwasupdatedon29November2021toreflectupgradestoVuex. Vuexisadouble-edgedsword.Ifusedproperly,itcanmakeyourlifealoteasierwhenworkingwithVue.Itcanalsomakeamessofyourcodebaseifyou’renotcareful. TherearefourmainconceptsyoushouldunderstandbeforeyouuseVuex:state,getters,mutations,andactions.AsimpleVuexstatemanipulatesdatawithintheseconceptsinthestore.MappinginVuexprovidesanice,cleanwayofretrievingdatafromthem. Inthistutorial,we’lldemonstratehowtomapdatafromtheVuexstore.Ifyou’reaVuedeveloperwho’sfamiliarwiththebasicsofVuex,thesebestpracticeswillhelpyouwritecleanerandmoremaintainablecode.Let’sgetstarted! Tableofcontents WhatisVuexmapping? VuexmapState WhenshouldyoumaptheentireVuexstate? WhatareVuexmapGetters? Vuexmapmutations MappingVuexactions WhatisVuexmapping? MappinginVuexenablesyoutobindanyofthestate’sproperties,likegetters,mutations,actions,orstate,toacomputedpropertyinacomponentandusedatadirectlyfromthestate. BelowisanexampleofasimpleVuexstorewithtestdatainthestate: importVuefrom'vue' importVuexfrom'vuex' Vue.use(Vuex) conststore=newVuex.Store({ state:{ data:"testdata" } } }) Ifyouwanttoaccessthevalueofdatafromthestate,addthefollowinginyourVue.jscomponent: computed:{ getData(){ returnthis.$store.state.data } } Theabovecodeworksbutquicklygetsuglyasdatainthestatestartstogrow.Forexample: importVuefrom'vue' importVuexfrom'vuex' Vue.use(Vuex) conststore=newVuex.Store({ state:{ user:{ id:1, age:23, role:user data:{ name:"username", address:"useraddress" } }, services:{}, medical_requests:{}, appointments:{}, } } }) Togettheusernamefromtheuserobjectinthestate: computed:{ getUserName(){ returnthis.$store.state.user.data.name } } Althoughwecangetthejobdonewiththis.$store.state.user.data.name,wecanuseamaphelpertosimplifyittothis.event. Wemadeacustomdemofor.Noreally.Clickheretocheckitout. Clickheretoseethefulldemowithnetworkrequests VuexmapState Tomapthestateinourcomponent,wefirstimportmapStateandaddacomputedpropertytoourcomponent: import{mapState}from'vuex'; exportdefault{ computed:{ ...mapState([ 'user', ]) } } Thethree-dotsyntaxusedaboveisanES6syntaxknownasthespreadsyntax.Younowhaveaccesstotheentireuserobjectwithinthecomponent,therefore,userbecomesacomputedcomponent.Youcandomore,likeaddingobjectsfromthestatetothemapStatemethod: import{mapState}from'vuex'; exportdefault{ computed:{ ...mapState([ 'user', 'services' ]) } } Asyoucansee,thiscodeisalotcleaner.Youcaneasilyaccesstheusernamewiththefollowing: {{user.data.name}} Thesamegoesfortheservicesobjectandmanyothervaluesmapped.DidyounoticehowwepassedinanarraytothemapState()?Ifyouneedtogivethevalueadifferentname,youcanpassinanobjectinsteadasfollows: import{mapGetters}from'vuex'; exportdefault{ computed:{ ...mapState({ userDetails:'user', userServices:'services' }) } } Now,youcanreferencetheuserbysimplycallinguserDetails. WhenshouldyoumaptheentireVuexstate? Atfirst,youshouldn’tmaptheVuexstate.Asaruleofthumb,youshouldmaptheVuexstateonlywhenyouhavealotofdatainthestateandneeditinthecomponent. Intheexampleabove,itwouldn’tmakemuchsensetomaptheentireuserobjectifweonlyneedonevaluefromit,forexample,theusername. Whenyoumapthestate,theentireobjectisloadedintomemory.Youshouldavoidloadingunnecessarydatatomemorybecauseitwouldleadtonegativeperformanceimplicationsinthelongrun. WhatareVuexmapGetters? Gettersprovideawaytogetaderivedcomputedstatefromthestore.MappinggettersissimilarinsyntaxtothemapStatefunction: import{mapGetters}from'vuex' exportdefault{ computed:{ ...mapGetters([ 'firstCount', 'anotherGetter', ]) } } Thecodeaboveissimilartowritingthecomputerpropertiesasfollows: exportdefault{ computed:{ firstCount(){ returnthis.$store.getters.firstCount }, anotherGetter(){ returnthis.$store.getters.anotherGetter }, } } Likethemappedstate,youcanpassinanobjecttothemapGettersfunctionifyouintendtouseadifferentname: import{mapGetters}from'vuex' exportdefault{ computed:{ ...mapGetters([ first:'firstCount', another:'anotherGetter', ]) } } Vuexmapmutations MutationisawaytochangestateintheVuexstore.UnlikemapStateandmapGetters,whicharemappedinthecomputedpropertyofVuetomakedataonthestatereactivewithdatainthecomponent,Mutationsaremappedinthemethod. Whenyoumapyourmutations,youcancommityourmutationusingthefollowingsyntaxinVue: this.$store.commit('mutationName`) Forexample: import{mapMutations}from'vuex' exportdefault{ methods:{ ...mapMutations([ 'search',//map`this.search()`to`this.$store.commit('search')` //`mapMutations`alsosupportspayloads: 'searchBy'//map`this.searchBy(key)`to`this.$store.commit('searchBy',key)` ]), } } MappingVuexactions Mappingactionsisalotlikemappingmutationsbecauseitisalsoperformedinthemethod.Actionsarealsomappedtothemethodspropertyandnotthecomputedproperty.Usingamapperbindsthis.$store.dispatch('actionName')tothenameinthearrayofthemapperorthekeyoftheobject: import{mapActions}from'vuex' exportdefault{ methods:{ ...mapActions([ 'search', //`mapActions`alsosupportspayloads:searchBy(key) 'searchBy' ]), } } Notehowweusedanarraytodefinemultiplemapactions,whichissimilartowritingthecomputerpropertiesasfollows: exportdefault{ methods:{ search(){ returnthis.$store.dispatch('search'); }, searchBy(key){ returnthis.$store.dispatch('searchBy',key); }, } } Conclusion Now,youshouldhaveafirmunderstandingofhowmappinginVuexworksandwhyyoushoulduseit.YoushouldbeabletomapallthecomponentsintheVuexstore,likestate,getters,mutations,andactions.Additionally,you’velearnedwhentomapthestoreandwhenyoushouldn’t. Anotheradvantageofmappingyouractions,getters,andmutationsisthatitwillmakeyourcodesmallerandsaveyousometimewriting. ThesebestpracticeswillhelpyouimmenselyifyoudecidetouseVuexinyournextproject.Ihopeyouenjoyedthistutorial. ExperienceyourVueappsexactlyhowauserdoesDebuggingVue.jsapplicationscanbedifficult,especiallywhentherearedozens,ifnothundredsofmutationsduringausersession.Ifyou’reinterestedinmonitoringandtrackingVuemutationsforallofyourusersinproduction,tryLogRocket.https://logrocket.com/signup/LogRocketislikeaDVRforwebandmobileapps,recordingliterallyeverythingthathappensinyourVueappsincludingnetworkrequests,JavaScripterrors,performanceproblems,andmuchmore.Insteadofguessingwhyproblemshappen,youcanaggregateandreportonwhatstateyourapplicationwasinwhenanissueoccurred.TheLogRocketVuexpluginlogsVuexmutationstotheLogRocketconsole,givingyoucontextaroundwhatledtoanerror,andwhatstatetheapplicationwasinwhenanissueoccurred.ModernizehowyoudebugyourVueapps-Startmonitoringforfree. Sharethis:TwitterRedditLinkedInFacebook MosesAnumaduFollow I'masoftwaredeveloperwithaninterestinwritingtechnicalarticlesandtutorials.Ihaveoverfouryearsofcodingexperiencewithvarioustechnologies.Ilovetoshareknowledgeintheformofwriting. Uncategorized #vue «Thecompleteguidetoblockchaintesting Whydon’tpeoplelikePHP?» DeepdiveintotheCSS:where()function PelumiAkintokun Mar22,2022 6minread MultithreadinginFlutterusingDartisolates AnvithBhat Mar22,2022 6minread WhyyoushoulduseaproxyserverwithCreate… JoelAdewole Mar22,2022 5minread 4Repliesto“BestpracticesforVuexmapping ” Goodguide:))Thankyousomuch,thisisjustthebeginningoflearningVUEoftherest,butthisentryisuseful. Ilikedyourexplanation,thank.Iobservedoneprobablemistake,youwrote“importmapGetters”intotheexplanationaboutmapState.That’sright? yourmutationmappingexampleismessedupman.namesaremismatched. thanksbutusageofmodules&nameSpacesismissing😉 LeaveaReplyCancelreply



請為這篇文章評分?