Best practices for Vuex mapping - LogRocket Blog
文章推薦指數: 80 %
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
延伸文章資訊
- 1【Day06】Vue-cli & Vuex mapState - CoderBridge
Day06 今天探討的是mapState,其他的map有空再補但其實都差不多。 會簡單的教學一下vue-cli建立專案,因為cdn一直沒辦法把map的部分搞定:(.
- 2Vuex状态管理-mapState的基本用法详细介绍 - CSDN博客
mapState()函数的返回结果是一个对象。 <template> <div id=" ...
- 3Best practices for Vuex mapping - LogRocket Blog
Vuex mapState; When should you map the entire Vuex state? What are Vuex mapGetters ? Vuex map mut...
- 4vuex state及mapState的基礎用法詳解 - 程式前沿
- 5[Vue.js] Vuex 學習筆記(6) - mapState 與mapGetters 合併使用
合併使用我們在實際開發時, computed 內容並不會像前兩章的範例那樣簡單,有時我們需要將本地組件的computed 或是mapState 與mapGetters 混合使用。