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.

Changing the icon to reflect the<br />

state<br />

Our ListingSave component's icon will appear differently, depending on whether<br />

or not the listing is saved; it will be opaque if the listing is saved, <strong>and</strong> transparent<br />

if it is not. Since the component doesn't store its state locally, we need to retrieve<br />

state from the store to implement this feature.<br />

<strong>Vue</strong>x store state should generally be retrieved via a computed property. This<br />

ensures that the component is not keeping its own copy, which would violate the<br />

single source of truth principle, <strong>and</strong> that the component is re-rendered when the<br />

state is mutated by this component or another. Reactivity works with <strong>Vue</strong>x state,<br />

too!<br />

Let's create a computed property isListingSaved, which will return a Boolean value<br />

reflecting whether or not this particular listing has been saved.<br />

resources/assets/components/ListingSave.vue: export default { props: [ 'id' ], methods: {<br />

toggleSaved() { this.$store.commit('toggleSaved', this.id); } }, computed: {<br />

isListingSaved() { return this.$store.state.saved.find(saved => saved ===<br />

this.id); } } }<br />

We can now use this computed property to change the icon. Currently we're<br />

using the Font Awesome icon fa-heart-o. This should represent the unsaved state.<br />

When the listing is saved we should instead use the icon fa-heart. We can<br />

implement this with a dynamic class binding.<br />

resources/assets/components/ListingSave.vue: <br />

export default { props: [ 'id' ], methods: { ... }, computed: {<br />

isListingSaved() { ...}, classes() { let saved = this.isListingSaved; return { 'fa':<br />

true, 'fa-lg': true, 'fa-heart': saved, 'fa-heart-o': !saved } } } } ...<br />

.listing-save .fa-heart { color: #ff5a5f; } <br />

Now the user can visually identify which listings have been saved <strong>and</strong> which

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

Saved successfully!

Ooh no, something went wrong!