Using Vue with existing web — server rendered — applications and websites
My go-to solution for making reusable components was defining blade template for each component that would include a
For those who don’t know what blade templates are, it’s a template engine of php’s Laravel framework, much like smarty and twigg, that makes it easier for developers to write structured view files, shortly they are html files that include dynamic parts of the view injected into the html output.
I had my trials of making those components in Angular but, I couldn’t really manage to make it simple enough, and when I was introduced to Vue JS, I was fascinated about how easy it is to create those components, the single file component — or the SFCs — concept brought me much closer to the goal of making simple readable reusable components and, use them normally within a blade view wherever required.
The main problem with SFCs that they require a build step, a
vue build or
vue-cli-service build command which implies setting up Vue CLI within your project and, manually run the command for each component you have.
So to solve that issue, at first I was defining the component’s html in a
# The component blade view file looks like this
<script type="text/x-template" id="my-template">
<!-- HTML content of the component here! -->
And in any page that I’d like to use any of those components I’ll
@include them in the page’s blade template, that way I didn’t need to build the components I develop however, stylesheet is now left out to be manually handled, so I had to write css files then include them in
link tags within the page view files, besides it’s a bit cumbersome to handle components this way so, I’ve decided to properly tackle the root challenge.
So, I’ve re-invented a part of an existing wheel, which is webpack and also probably Laravel Mix, luckily in the default Laravel project we have
packages.json file present so, I’ve included all Vue CLI services required to build SFCs as development dependencies by running
npm install --save-dev [required vue-cli packages] replacing the bracket with the packages needed for Vue CLI to work, I got the packages by creating a dummy Vue project and getting the required dependencies listed in its
And just by running the script all pages required components are built in one shot, or optionally you can pass the name of the module and page, to build only the components of the specified module or page. The following gist explains how it’s done in more detail.
And that’s how I managed to handle using vue components in a conventional old-school multi page web application. I hope this is helpful enough for backend web developers out there, as this could be the entry point to the frontend development realm.
And as always, thanks for reading.