一、组件的本质与使用前提
在 Vue 中:
组件 = 可复用的 UI + 行为单元
使用组件的前提是:先导入(import),再注册(register),最后使用
<template> <MyComponent /> </template>二、组件的创建(基础回顾)
一个标准 Vue 3 组件(SFC):
<!-- components/HelloWorld.vue --> <template> <div>Hello World</div> </template> <script setup lang="ts"> </script>三、组件注册方式总览(重点)
Vue 3 中常见的组件注册方式有4 种:
| 注册方式 | 使用范围 | 是否推荐 |
|---|---|---|
| 局部注册 | 当前组件 | 强烈推荐 |
| 全局注册 | 整个应用 | 谨慎使用 |
<script setup>自动注册 | 当前组件 | 强烈推荐 |
| 自动导入(插件) | 整个项目 | 企业级推荐 |
四、局部注册(最常用、最安全)
1. Options API(传统写法)
<script> import HelloWorld from '@/components/HelloWorld.vue' export default { components: { HelloWorld } } </script> <template> <HelloWorld /> </template>特点
作用域清晰
不污染全局
Tree Shaking 友好
2. Composition API(非 script setup)
<script> import { defineComponent } from 'vue' import HelloWorld from '@/components/HelloWorld.vue' export default defineComponent({ components: { HelloWorld } }) </script>五、<script setup>中的组件注册(Vue 3 主流)
核心结论(非常重要)
在
<script setup>中:只要 import,就等于注册
示例
<script setup lang="ts"> import HelloWorld from '@/components/HelloWorld.vue' </script> <template> <HelloWorld /> </template>原理说明(简述)
<script setup>是编译期语法糖编译器会自动把
import的组件注入到模板作用域不再需要
components: {}
命名规则说明
import MyButton from './MyButton.vue'模板中两种写法都可以:
<MyButton /> <my-button />推荐:组件文件名用 PascalCase
六、全局组件注册(不推荐滥用)
1. 全局注册方式
// main.ts import { createApp } from 'vue' import App from './App.vue' import BaseButton from '@/components/BaseButton.vue' const app = createApp(App) app.component('BaseButton', BaseButton) app.mount('#app')使用
<BaseButton />使用场景(合理)
基础组件(Button / Icon / Modal)
UI 框架封装组件
不依赖业务上下文的组件
不推荐原因
组件来源不清晰
不利于 Tree Shaking
大型项目中可维护性差
七、组件的异步注册(性能优化)
1. 使用defineAsyncComponent
<script setup> import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent(() => import('@/components/HeavyComponent.vue') ) </script> <template> <AsyncComp /> </template>适用场景
页面级组件
体积大的组件
非首屏内容
八、自动导入组件(企业级方案)
在 Vue 3 + Vite 项目中,强烈推荐使用自动导入方案。
1. 使用unplugin-vue-components
npm install -D unplugin-vue-components2. Vite 配置
// vite.config.ts import Components from 'unplugin-vue-components/vite' export default { plugins: [ Components({ dirs: ['src/components'], extensions: ['vue'], deep: true }) ] }3. 使用(无需 import)
<template> <HelloWorld /> </template>优点
无需手动 import
支持按需加载
组件使用体验接近全局组件但更安全
九、组件注册常见错误与排查
1. 组件未注册
Failed to resolve component排查顺序:
是否
import路径是否正确
是否大小写不一致
是否
<script setup>
2. 文件名大小写问题(Linux 下常见)
import helloworld from './HelloWorld.vue' // 错误3. 使用了但未导入
<template> <HelloWorld /> </template>但<script setup>中没有 import
十、最佳实践总结(工程经验)
推荐组件使用策略
| 场景 | 推荐方案 |
|---|---|
| 业务组件 | 局部注册 / script setup |
| 页面组件 | 异步组件 |
| 基础组件 | 全局或自动导入 |
| 中大型项目 | 自动导入 + 局部注册 |