Getting Started with Vue.js: Lesson 21 of 25

Registering Components

Up Next

Organizing Components

Autoplaying in 7 seconds!

Cancel

So far, we have been registering components globally. This could become problematic because adding things globally could result in some naming collisions.

Let's say you named your gif-box gif instead and you brought in another external package named the same. That's a rare occasion, but if there are more naming conventions like slider where collisions are more likely.

Registering Components Per Vue Instance

Instead of registering our components globally, we can register them per Vue instance so that only that Vue instance will know to use that component.

Table of Contents

    This is helpful because it also is a sign to us as the developer that this Vue application will use these components. We're big supporters of readability and explicitly saying what dependencies live where.

    Registering globally uses the Vue.component({ }) syntax. To register locally, we'll create an object:

    const GifGrid = {
      props: ['gifs'],
      components: {
        'gif-box': GifBox
      },
      template: `
        <div class="columns is-multiline" v-if="gifs">
          <div class="column is-one-third" v-for="gif in gifs">
    
            <gif-box :gif="gif"></gif-box>
    
          </div>
        </div>
      `
    };

    Instead of Vue.component({ }), we are using const GifGrid = { }. Once we have our object, we can tell Vue to look at that object when creating its Vue instance and components.

    Naming convention for components is StudlyCaps.

    We'll pass in a components property to our Vue instance:

    const app = new Vue({
      el: '#app',
    
      components: {
        'gif-grid': GifGrid
      }, 
    
      ...
    
    });

    Here we define the custom selector we want (gif-grid) and then tell it what object to use.

    Component Can Use Other Components

    Just like we defined a GifGrid component locally inside our main Vue instance, we can define the GifBox as well. Instead of defining it in our Vue instance though, we'll register the GifBox inside of the GifGrid component since GifGrid will always need the GifBox.

    This is also helpful because when we want to use the GifGrid, we don't have to add two components to our Vue instance.

    const GifBox = {
        ...
    };
    
    const GifGrid = {
        props: ['gifs'],
        components: {
            'gif-box': GifBox
        },
        ...  
     };

    Now we are starting to see how our application is turning into a tree of components from the top Vue instance to the nested child components.

    Chris Sevilleja

    173 posts

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