Structuring a Vue.js application
And keeping those concerns separated!
As my (very esteemed) colleague Tim Sommer (check out his blog!) put it: it’s AngularJS done right.
All Is Not Well
I was happy to learn that Vue is based heavily on using components. I was not happy, however, to learn that Vue supports single-file components. Especially because most tutorials or guides will tell you to simply dump all your
Component.Vue files in one folder,
Fortunately, the team behind Vue.JS is aware that devs might be bothered by this, so they offer an alternative in their guide: we can reference
style files in our Vue files.
Take, for example, the following
App.Vue single-file component:
We can split this up into three files, effectively separating each by their own concern:
Naturally, since our components now comprise 3 files instead of 1, it makes sense to group these in their own folder under
src\components, in this case:
Views vs Components
app.view.js , instead of simply
app.js. To import our App-component, we would use the following statement:
app.js because the import statement would match and return that file instead of the
However, there’s more reasoning behind the
.view. When you use Vue-Router, routes are mapped to components. Components matched by routes are, in my experience, rarely reused and are usually comprised of other, reusable components. The way I see it, they are simply views, combining smaller components to create one screen. Such a view is always a component, but a component isn’t necessarily a view.
To easily navigate through larger-scale projects, I tend to make a separate
views folder in
src to contain these view-components.
Learn By Example
Let’s assume we’re building an app that, among others, has a view that lists users. Using the ideas laid out above, we could structure our Vue.JS app like so:
Structuring your app like this makes navigating your project a breeze and allows for easier cooperation when working in teams.