Tutorials References Exercises Bootcamps Videos Menu
Sign Up Create Website Get Certified Upgrade

Local Components

The way we have included components so far makes them accessible from all *.vue files in a project.

Components can be made to be local, meaning that they are only accessible inside a specific *.vue file.

Global Components

The way we have included components inside main.js so far make the components accessible inside the <template> of all other *.vue files in that project.

Example

We use the CompOne.vue component inside both CompTwo.vue and App.vue to show that components are accessible to each other with our current main.js setup.

main.js:

import { createApp } from 'vue'
 
import App from './App.vue'
import CompOne from './components/CompOne.vue'
import CompTwo from './components/CompTwo.vue'

const app = createApp(App)
app.component('comp-one', CompOne)
app.component('comp-two', CompTwo)
app.mount('#app')
Run Example »

Local Components

We can include a component directly in the <script> tag in a *.vue file instead of including it in main.js.

If we include a component directly in a *.vue file, the component beomes accessible only locally in that file.

Example

To make CompOne.vue local to App.vue, and only accessible there, we remove it from main.js.

main.js:

import { createApp } from 'vue'
 
import App from './App.vue'
import CompOne from './components/CompOne.vue' 
import CompTwo from './components/CompTwo.vue'
 
const app = createApp(App)
app.component('comp-one', CompOne) 
app.component('comp-two', CompTwo)
app.mount('#app')

And include CompOne.vue directly in the <script> tag of App.vue instead.

App.vue:

<template>
  <h3>Local Component</h3>
  <p>The CompOne.vue component is a local component and can only be used inside App.vue.</p>
  <comp-one />
  <comp-two />
</template>

<script> 
  import CompOne from './components/CompOne.vue';

  export default {
    components: {
      'comp-one': CompOne
    }
  }
</script>
Run Example »

The CompOne.vue component is now only available in App.vue.

If you run the application in development mode and try to use CompOne.vue from inside CompTwo.vue you get a warning:


Vue Exercises

Test Yourself With Exercises

Exercise:

How can we make the 'comp-one' component available locally, only to one component?

<script> 
 CompOne from './components/CompOne.vue';

  export default {
    : {
      'comp-one': 
    }
  }
</script>

Start the Exercise