Getting Started with Vue.js: Lesson 22 of 25

Organizing Components

Up Next

Using the Vue CLI

Autoplaying in 7 seconds!

Cancel

When we want to build larger and more scalable applications, it makes sense to start separating our code out into multiple files. This file is already starting to become unwieldly because all the code is in this file:

  • Gif Grid component
  • Gif Box component
  • Main Vue app code

As a simple organizational tactic, we can start to organize into separate files and import using <script> tags.

Creating Separate Files

We can create two files and add their respective code in each:

Table of Contents

    • /js/gif-grid.js
    • /js/gif-box.js

    Copy the const GifGrid = {} and const GifBox = {} into their rightful files. Then import them in the following order:

    <script src="https://unpkg.com/vue"></script>
    <script src="./js/components/gif-box.js"></script>
    <script src="./js/components/gif-grid.js"></script>

    Remember, order is important since GifGrid needs GifBox to work. GifBox needed to be loaded first.

    A More Scalable Approach

    While <script> tags are fine for small applications like this, it is better to bring in a tool like webpack and start to use ES6 imports like so:

    import { GifBox } from './gif-box';

    That goes beyond the scope of this course, but it is good to start to think in ES6 imports. This gives us a few benefits:

    • We know exactly what is getting imported and where it comes from
    • We don't need to worry about order of <script> tags
    • Other developers can come into this project and know what dependencies are needed

    We'll explore more on this technique in the coming courses when we build larger Vue apps.

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.