浅谈Vue3|浅谈Vue3 defineComponent有什么作用
目录
- defineComponent重载函数
- 开发实践
export function defineComponent(options: unknown) {return isFunction(options) ? { setup: options } : options}
defineComponent最重要的是:在TypeScript下,给予了组件 正确的参数类型推断 。

文章图片
defineComponent重载函数 1:direct setup function
// overload 1: direct setup function// (uses user defined props interface)export function defineComponent(setup: (props: Readonly,ctx: SetupContext) => RawBindings | RenderFunction): DefineComponent

文章图片
2:object format with no props
// overload 2: object format with no props// (uses user defined props interface)// return type is for Vetur and TSX supportexport function defineComponent(options: ComponentOptionsWithoutProps): DefineComponent

文章图片
3:object format with array props declaration
// overload 3: object format with array props declaration// props inferred as { [key in PropNames]?: any }// return type is for Vetur and TSX supportexport function defineComponent(options: ComponentOptionsWithArrayProps ): DefineComponent ,RawBindings,...>

文章图片
4: object format with object props declaration
// overload 4: object format with object props declaration// see `ExtractPropTypes` in ./componentProps.tsexport function defineComponent/ the Readonly constraint allows TS to treat the type of { required: true }// as constant instead of boolean.PropsOptions extends Readonly,RawBindings,D,C extends ComputedOptions = {},M extends MethodOptions = {},Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,Extends extends ComponentOptionsMixin = ComponentOptionsMixin,E extends EmitsOptions = Record,EE extends string = string>(options: ComponentOptionsWithObjectProps ): DefineComponent

文章图片
开发实践 除去单元测试中几种基本的用法,在以下的 ParentDialog 组件中,主要有这几个实际开发中要注意的点:
自定义组件和全局组件的写法
inject、ref 等的类型约束
setup 的写法和相应 h 的注入问题
tsx 中 v-model 和 scopedSlots 的写法
ParentDialog.vue
全文总结
- 引入 defineComponent() 以正确推断 setup() 组件的参数类型
- defineComponent 可以正确适配无 props、数组 props 等形式
- defineComponent 可以接受显式的自定义 props 接口或从属性验证对象中自动推断
- 在 tsx 中,element-ui 等全局注册的组件依然要用 kebab-case 形式
- 在 tsx 中,v-model 要用 model={ { value, callback }} 写法
- 在 tsx 中,scoped slots 要用 scopedSlots={ { foo: (scope) => () }} 写法
- defineComponent 并不适用于函数式组件,应使用 RenderContext 解决
推荐阅读
- 性能测试中QPS和TPS的区别
- 浅谈教育与医学之本质和医学生培养之三观
- 浅谈朋友圈
- 《浅谈减压方式在趣味首饰中的表现》
- 浅谈iOS|浅谈iOS 11.0中UITableView 都更改了什么( (二))
- 浅谈智慧课堂
- 浅谈如何赏析诗词
- 浅谈股市
- 《浅谈宗教信仰与践行科学的理想信念》
- vue|vue3替代vuex的框架piniajs实例教程