六 分分钟学会 注册 全局和局部组件

98 阅读1分钟

1. 全局组件

组件注册成全局组件后,可以在全局直接使用

(1)新建自定义组件 CustomComponent.vue

<template>
    <div>
        我是自定义组件
    </div>
</template>

<script setup>

</script>

<style lang="scss" scoped>

</style>

(2)引入并注册全局组件


import { createApp } from 'vue'

// 引入自定义组件
import CustomComponent from "@/components/CustomComponent.vue";

import App from './App.vue'

const app = createApp(App)

// 注册全局组件
app.component('aaaaCom', CustomComponent)

app.mount('#app')


(3)使用自定义的全局组件

<template>
  <div class="about">
    <aaaaCom></aaaaCom>
  </div>
</template>

<script setup lang="ts">
</script>

2. 局部组件

局部组件使用时,需要在使用的文件内单独引用

(1)新建自定义组件 CustomComponent.vue

<template>
    <div>
        我是自定义组件
    </div>
</template>

<script setup>

</script>

<style lang="scss" scoped>

</style>

(2)使用自定义的局部组件

组件的使用方式 可以使用 大驼峰(PascalCase) ,也可以将大坨峰 改成(kebab-case)


<template>
  <div class="about">

    <!-- 使用自定义组件 方式一 -->
    <CustomComponent></CustomComponent>

    <!-- 使用自定义组件 方式二 -->
    <custom-component />
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from "@/components/CustomComponent.vue";


</script>