Vue3学习笔记(1):组件
vue3 已经发布到 3.2 版本了,快来一起学习一下吧!
不过因为 Vue3 已经通过 ts 进行重写了,所以在学习 vue3 之前最好还是先学习一下 ts 的基本使用哦!
组件定义
在 vue3 中,定义组件主要是通过:defineComponent
来定义,而不能向 vue2 一样直接export
导出。
基本用法是先从 vue 依赖导入defineComponent
函数,然后再export default defineComponent
导出该组件,看起来就像这样:
1 | import { defineComponent } from 'vue' |
defineComponent 讲解
下载 vue 官方的 vue-next 仓库,查看相关的源码,先看一下 DefineComponent 类型:
1 | export type DefineComponent< |
建议动手下载一下源码,并去查看一下上面提到的一些类型,比如:ComputedOptions
、ComponentPublicInstanceConstructor
等等,想想为什么要这么写,想不到其实也没关系,其实这就是为了符合 TypeScript 的类型声明的理念。
通过查看ComponentPublicInstanceConstructor
层层类型定义的嵌套,可以找到最终的一个类型定义
1 | // public properties exposed on the proxy, which is used as the render context |
可以看到上面熟悉的:$data
、$refs
、$parent
等等,这就是最终生成的组件的定义。
继续看主要内容:defineComponent
,下面是四种不同的defineComponent
函数的重载
1 | // defineComponent is a utility that is primarily used for type inference |
可以看到真正定义 defineComponent
函数的代码只有三行,其他的都是类型定义。
组件的定义
既然上面了解了defineComponent
,那么现在尝试去使用一下这个函数,这是一个非常基础的组件的定义:
1 | import { defineComponent, PropType } from 'vue' |
上面的String
,Number
这些其实只是一个类,如果要符合 ts,最正统的应该加上as
将该值视为 xxx 类型。如果有些场景不加 as 的话:
1 | export default defineComponent({ |
在 vscode 编辑器下,把鼠标放到:this.config
上,可以看到 vscode 提示:(property) config?: Record<string, any> | undefined
说明如果不定义类型的话那么 config 的值将会是 any 类型。对于 ts 来说这样可以用,但是 any 对于我们来说始终是不好的东西。我们应该这样去做:
1 | interface Config { |
这样我们去看 config 的类型:(property) config?: Config | undefined
。
可以看到该类型还有可能是undefined
,如果不能让他为undefined
只需要加上required
。
1 | export default defineComponent({ |
最终我们看到 config 类型是:(property) config: Config
,因为声明了该 prop 是必传的,所以他肯定是有值的,那就必不可能是undefined
。
如果上面不设置,直接调用this.config.name
那么 TS 编译器则会报错:Object is possibly 'undefined'
。如果没有 required 去设置的话,你可能还要使用if (this.config)
去调用this.config.name
,那么如果有 required 的话将不再担心这些,可以直接去调用,这就是 ts 的好处。这样就能提高我们写代码的自信,因为 ts 没给我们报错,那么我们的代码出错的几率就会降低。
上面就是组件相关的一些内容,下一节开始将深入讲解 props。