In this post I’ll explain our current approach in detail.
Blade or Vue single file components?
Our approach is to organise our JS code per page. Utilising the relatively new dynamic import feature, we only load the code needed for a specific page. Suppose we wrote some code for the homepage only, for example, a scroll-to-top button. Put this code in a module that exports it as a default function:
This is how we would load this code in app.js
Vue SFC in blade template
Suppose we have a review page where reviews are shown in a slider that is built with Vue. We would implement this (in app.js) like so:
In the blade template we would need to add <review-slider></review-slider> inside some div with id block_reviews to make it work. The component will only be loaded on the reviews page. We use the excellent vue-slick-carousel package to create the slider, but it’s outside the scope of this post to explain the complete ReviewSlider component.
Vue SPA on a page
Suppose we have another page (e.g., contact) with a lot of user interactions. We decided to make it a SPA inside that specific Laravel page. The blade template is very straightforward, it simply contains a single <div id=”my-spa”></div>. We would arrange this in app.js like so:
Or, with dynamic importing of the component, it looks like this:
The component ContactContainer is mounted to the div#my-app. This means that the div itself is replaced by the template of the component. This component now handles everything on the page, for example
- show contact form and submit (with validation and response feedback)
- show Google map with navigation options
- show helpdesk widget to chat with the company
Summary and conclusion
- import an ES6 module with JS you wrote yourself
- import a Vue SFC and use it in the blade template
- import a Vue SFC and transform the page to a SPA
In the near future we will extend this post with our experiences with the Laravel Jetstream package for scaffolding the frontend.