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.
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.
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 »
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.
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:
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!