loading

Vue Local Components

Thus far, we have integrated components in a way that allows them to be accessed from any *.vue file within a project.

It is possible to make components local, which restricts their accessibility to within a certain *.vue file.

Global Components

The components are currently accessible inside the <template> of all other *.vue files in that project due to the manner we have included them inside main.js.

Example

To demonstrate that components can communicate with one another using our present main.js setup, we employ the CompOne.vue component inside both CompTwo.vue and App.vue.

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')
				
			

Local Components

Rather than including a component in main.js, we can include it directly in the <script> tag in a *.vue file.

A component can only be accessed locally within a *.vue file if it is included explicitly in that file.

Example

We take CompOne.vue out of main.js to make it local to App.vue and only available there.

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')
				
			

Instead, include CompOne.vue straight within App.vue is <script> tag.

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>
				
			

At this time, CompOne.vue is exclusively available in App.vue.

A warning appears if you attempt to use CompOne.vue from within CompTwo.vue when the program is running in development mode.

Vue Local Components -
Share this Doc

Vue Local Components

Or copy link

Explore Topic