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.

Moving the solution to a mixin<br />

Let's generalize the solution for getting the right data to the home page so that<br />

we can use it on the listing page as well. To do this, we'll move Axios <strong>and</strong> the<br />

beforeRouteEnter hook from the HomePage component into a mixin that can then be<br />

added to both page components: $ touch resources/assets/<strong>js</strong>/route-mixin.<strong>js</strong><br />

At the same time, let's improve the code by removing the repetition of the next<br />

function call. To do this, we'll create a new method, getData, which will be<br />

responsible for figuring out where to get the right data for the page <strong>and</strong> also for<br />

getting it. Note that this method will be asynchronous since it may need to wait<br />

for AJAX to resolve, so it will return a Promise rather than an actual value. This<br />

Promise is then resolved within the navigation guard.<br />

resources/assets/<strong>js</strong>/route-mixin.<strong>js</strong>: import axios from 'axios';<br />

function getData(to) { return new Promise((resolve) => { let serverData =<br />

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

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

}); } else { resolve(serverData); } }); }<br />

export default { beforeRouteEnter: (to, from, next) => { getData(to).then((data)<br />

=> { next(component => component.assignData(data)); }); } };<br />

We don't need a polyfill for Promise as that is already supplied in<br />

the Axios library.

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

Saved successfully!

Ooh no, something went wrong!