25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Getters<br />

Sometimes what we want to get from the store is not a direct value, but a derived<br />

value. For example, say we wanted to get only those listing summaries that were<br />

saved by the user. To do this, we can define a getter, which is like a computed<br />

property for the store: state: { saved: [5, 10], listing_summaries: [ ... ] }, getters:<br />

{ savedSummaries(state) { return state.listing_summaries.filter( item =><br />

state.saved.indexOf(item.id) > -1 ); } }<br />

Now, any component that needs the getter data can retrieve it from the store as<br />

follows: console.log(this.$store.state.getters.savedSummaries); /* [ 5 => [ ... ],<br />

10 => [ ... ] ] */<br />

Generally, you define a getter when several components need the same derived<br />

value, to save repeating code. Let's create a getter which retrieves a specific<br />

listing. We've already created this functionality in ListingPage, but since we're<br />

going to need it in our router as well, we'll refactor it as a getter.<br />

One thing about getters is that they don't accept a payload argument like<br />

mutations do. If you want to pass a value to a getter, you need to return a<br />

function where the payload is an argument of that function.<br />

resources/assets/<strong>js</strong>/router.<strong>js</strong>: getters: { getListing(state) { return id =><br />

state.listings.find(listing => id == listing.id); } }<br />

Let's now use this getter in our ListingPage to replace the previous logic.<br />

resources/assets/components/ListingPage.vue: computed: {<br />

listing() { return populateAmenitiesAndPrices(<br />

this.$store.getters.getListing(this.$route.params.listing) ); }<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!