I'm a big fan and user of Vue.js for frontend work that isn't just a basic web page. It's super easy to use when starting out with the 1st-party Vue-cli. However due to the nature of the projects I work on, I'm not always able to have the luxury of choosing how I bootstrap the frontend. Recently a co-worker asked for my help and I got stumped temporarily. Here's the breakdown
We had a Blade template in a Laravel project. We injected app.js
in the footer using Laravel Mix to handle our Webpack config. We included the Vue dependency through npm
, and had to setup the Vue app in `app.js like so:
window.Vue = require('vue');
const app = new Vue({
el: '#app',
template: `{ /* Markup goes here */ } `
})
My co-worker had then proceeded by adding a template
key to the Vue instantiation within the const app
. This got messy and also suffered from a lack of template highlighting. We decided to break the markup in template
into single file components (SFC) using the .vue
suffix. We scratched our heads a bit and came up with this, which worked:
window.Vue = require('vue');
Vue.component('MyComponent', require('./components/myComponent.vue').default);
const app = new Vue({
el: '#app',
});
We could then drop <my-component>
into the Blade template wherever we liked, as long as it was inside an element with an id of app
, such as <div id="app"></div>
.
To reiterate, this is for Vue apps that don't use the CLI or Webpack to kick off a dev server. This is if you want to have Vue load from a CDN link or be a globally available library and then have a simple app.js
file kick off the app itself.
Such a small problem I know, but since it was something new I learned today, I decided to make a quick blog about it so that others may find the solution too.