# 深入组件 ## 组件注册 ### 全局注册 ```js import { createApp } from 'vue' const app = createApp({}) app.component( // 注册的名字 'MyComponent', // 组件的实现 { /* ... */ } ) // 单文件组件 import MyComponent from './App.vue' app.component('MyComponent', MyComponent) // .component() 方法可以被链式调用 app .component('ComponentA', ComponentA) .component('ComponentB', ComponentB) .component('ComponentC', ComponentC) ``` ### 命名 - PascalCase:大驼峰 ## Props ### Props 声明 - 使用 ` ``` - 没有使用 ` ``` ### 单向数据流 - 不能重新赋值props - 能修改引用类型,但是会造成损耗不推荐 ### Prop 校验 ```js defineProps({ // 基础类型检查 // (给出 `null` 和 `undefined` 值则会跳过任何类型检查) propA: Number, // 多种可能的类型 propB: [String, Number], // 必传,且为 String 类型 propC: { type: String, required: true }, // Number 类型的默认值 propD: { type: Number, default: 100 }, // 对象类型的默认值 propE: { type: Object, // 对象或数组的默认值 // 必须从一个工厂函数返回。 // 该函数接收组件所接收到的原始 prop 作为参数。 default(rawProps) { return { message: 'hello' } } }, // 自定义类型校验函数 // 在 3.4+ 中完整的 props 作为第二个参数传入 propF: { validator(value, props) { // The value must match one of these strings return ['success', 'warning', 'danger'].includes(value) } }, // 函数类型的默认值 propG: { type: Function, // 不像对象或数组的默认,这不是一个 // 工厂函数。这会是一个用来作为默认值的函数 default() { return 'Default function' } } }) ``` ## 组件事件 ```vue ``` ![](./vue3深入组件.assets/3d9f574cc12244ecb8dcab9ef49d7697.png) ### 事件参数 ```vue ``` ### 声明触发的事件 - 我们在 `