Getters | Vuex

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

Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. WARNING. As of Vue 3.0, the getter's ... GuideAPIReferenceReleaseNotesv4.xv3.xLanguagesEnglish简体中文日本語PortuguêsGitHubIntroductionWhatisVuex?InstallationGettingStartedCoreConceptsStateGettersProperty-StyleAccessMethod-StyleAccessThemapGettersHelperMutationsActionsModulesAdvancedApplicationStructureCompositionAPIPluginsStrictModeFormHandlingTestingHotReloadingTypeScriptSupportMigrationGuideMigratingto4.0from3.xGetters#TrythislessononScrimbaSometimeswemayneedtocomputederivedstatebasedonstorestate,forexamplefilteringthroughalistofitemsandcountingthem:computed:{ doneTodosCount(){ returnthis.$store.state.todos.filter(todo=>todo.done).length } } Ifmorethanonecomponentneedstomakeuseofthis,wehavetoeitherduplicatethefunction,orextractitintoasharedhelperandimportitinmultipleplaces-botharelessthanideal.Vuexallowsustodefine"getters"inthestore.Youcanthinkofthemascomputedpropertiesforstores.WARNINGAsofVue3.0,thegetter'sresultisnotcachedasthecomputedpropertydoes.ThisisaknownissuethatrequiresVue3.1tobereleased.YoucanlearnmoreatPR#1878.Getterswillreceivethestateastheir1stargument:conststore=createStore({ state:{ todos:[ {id:1,text:'...',done:true}, {id:2,text:'...',done:false} ] }, getters:{ doneTodos(state){ returnstate.todos.filter(todo=>todo.done) } } }) Property-StyleAccess#Thegetterswillbeexposedonthestore.gettersobject,andyouaccessvaluesasproperties:store.getters.doneTodos//->[{id:1,text:'...',done:true}] Getterswillalsoreceiveothergettersasthe2ndargument:getters:{ //... doneTodosCount(state,getters){ returngetters.doneTodos.length } } store.getters.doneTodosCount//->1 Wecannoweasilymakeuseofitinsideanycomponent:computed:{ doneTodosCount(){ returnthis.$store.getters.doneTodosCount } } NotethatgettersaccessedaspropertiesarecachedaspartofVue'sreactivitysystem.Method-StyleAccess#Youcanalsopassargumentstogettersbyreturningafunction.Thisisparticularlyusefulwhenyouwanttoqueryanarrayinthestore:getters:{ //... getTodoById:(state)=>(id)=>{ returnstate.todos.find(todo=>todo.id===id) } } store.getters.getTodoById(2)//->{id:2,text:'...',done:false} Notethatgettersaccessedviamethodswillruneachtimeyoucallthem,andtheresultisnotcached.ThemapGettersHelper#ThemapGettershelpersimplymapsstoregetterstolocalcomputedproperties:import{mapGetters}from'vuex' exportdefault{ //... computed:{ //mixthegettersintocomputedwithobjectspreadoperator ...mapGetters([ 'doneTodosCount', 'anotherGetter', //... ]) } } Ifyouwanttomapagettertoadifferentname,useanobject:...mapGetters({ //map`this.doneCount`to`this.$store.getters.doneTodosCount` doneCount:'doneTodosCount' }) StateMutations



請為這篇文章評分?