Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

本地组件

到目前为止,我们包含组件的方式使它们在项目中的所有 *.vue 文件中都可以访问。

组件可以设置为本地,这意味着它们只能在特定的 *.vue 文件中访问。

全局组件

到目前为止,我们在 main.js 中包含组件的方式使组件在该项目中所有其他 *.vue 文件的 <template> 中都可以访问。

示例

我们在 CompTwo.vueApp.vue 中都使用了 CompOne.vue 组件,以表明组件在当前的 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')
运行示例 »

本地组件

我们可以将组件直接包含在 *.vue 文件的 <script> 标签中,而不是包含在 main.js 中。

如果我们直接在 *.vue 文件中包含组件,则该组件仅在该文件内本地可用。

示例

要使 CompOne.vue 成为 App.vue 的本地组件,并且只能在 App.vue 中访问,我们将它从 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')

并将 CompOne.vue 直接包含在 App.vue<script> 标签中。

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>
运行示例 »

CompOne.vue 组件现在仅在 App.vue 中可用。

如果您在开发模式下运行应用程序并尝试从 CompTwo.vue 中使用 CompOne.vue,您将收到警告


Vue 练习

通过练习测试自己

练习

我们如何使 'comp-one' 组件在本地可用,仅对一个组件可用?

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

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

开始练习



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.