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.

Router<br />

The logic for retrieving page state is in the mixin file route-mixin.<strong>js</strong>. This mixin<br />

adds a beforeRouteEnter hook to a page component which applies the page state to<br />

the component instance when it becomes available.<br />

Now that we're storing page state in <strong>Vue</strong>x we will utilize a different approach.<br />

Firstly, we won't need a mixin anymore; we'll put this logic into router.<strong>js</strong> now.<br />

Secondly, we'll use a different navigation guard, beforeEach. This is not a<br />

component hook, but a hook that can be applied to the router itself, <strong>and</strong> it is<br />

triggered before every navigation.<br />

You can see in the following code block how I've implemented this in router.<strong>js</strong>.<br />

Note that before next() is called we commit the page state to the store.<br />

resources/assets/<strong>js</strong>/router.<strong>js</strong>: ...<br />

import axios from 'axios'; import store from './store';<br />

let router = new <strong>Vue</strong>Router({ ... });<br />

router.beforeEach((to, from, next) => { let serverData =<br />

JSON.parse(window.vuebnb_server_data); if (!serverData.path || to.path !==<br />

serverData.path) { axios.get(`/api${to.path}`).then(({data}) => {<br />

store.commit('addData', {route: to.name, data}); next(); }); } else {<br />

store.commit('addData', {route: to.name, data: serverData}); next(); } });<br />

export default router;<br />

With that done, we can now delete the route mixin: $ rm<br />

resources/assets/<strong>js</strong>/route-mixin.<strong>js</strong>

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

Saved successfully!

Ooh no, something went wrong!