25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Responding to authenticated<br />

state<br />

Now that we're tracking the authentication state of the user, we can get <strong>Vue</strong>bnb<br />

to respond to it. For one, let's make it so that a user can't save a listing unless<br />

they're logged in. To do this, we'll modify the behavior of the toggleSaved mutator<br />

method so that if the user is logged in they can save an item, but if not they are<br />

redirected to the login page via the push method of <strong>Vue</strong> Router.<br />

Note that we'll have to import our router module at the top of the file to access<br />

its features.<br />

resources/assets/<strong>js</strong>/store.<strong>js</strong>: ... import router from './router'; export default new<br />

<strong>Vue</strong>x.Store({ ... mutations: { toggleSaved(state, id) { if (state.auth) { let index =<br />

state.saved.findIndex(saved => saved === id); if (index === -1) {<br />

state.saved.push(id); } else { state.saved.splice(index, 1); } } else {<br />

router.push('/login'); } }, ... }, ... });<br />

We'll also make it so that either the login link or the logout link is shown in the<br />

toolbar, never both. This can be achieved by using v-if <strong>and</strong> v-else directives in<br />

the toolbar that depend on the $store.state.auth value.<br />

It would also make sense to hide the saved page link unless the user is logged in,<br />

so let's do that as well.<br />

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

Saved Log Out Log In

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

Saved successfully!

Ooh no, something went wrong!