SFC 单文件组件
顾名思义,就是一个.vue
文件只写一个组件
模板写法

如果这个组件想要在别的组件里使用,就需要在另一个.vue
中引入和使用、复用
h函数写法
使用 defineComponent + h
去进行组件编写

JSX/TSX写法
使用 defineComponent + JSX/TSX
去进行组件编写
pnpm i @vitejs/plugin-vue-jsx -D
安装完毕后,需要在 vite.config.ts
中去进行插件配置



引入组件

单文件多复用模板
如果你想要在一个单文件组件中,定义一些可复用的模板代码的话,可以试试以下的方法
createReusableTemplate

这是 VueUse
提供的一个 Hooks
使用方式如下:

namedTemplate

namedTemplate
是 Vue Macros
推出的一个前瞻性的 Vue3 特性
虽然Vue Macros
里的特性暂时还不是正式版特性,但是以后有很大概率会成为正式版特性
我们也可以对 Vue3 项目进行配置,使得项目可以使用 Vue Macros
的特性
文档地址:https://vue-macros.dev/zh-CN/features/named-template.html
使用方式如下:

通用的多组件管理
你可以将多个逻辑紧密或者类型相似的组件,放置在同一个ts
文件或Hooks
中去管理,在使用到这些组件的地方去引入即可使用~
FunctionalComponent + h
在某一个页面中,如果你有一些组件,它们逻辑比较紧密联系,那你可以使用FunctionalComponent + h
将他们封装在同一个 Hooks 中,比如下面的例子



或者你不想写在Hooks
中,你也完全可以写在最外层

只不过引入方式就要做一些改变

defineComponent + h
defineComponent + h
的写法也是差不多的道理
你可以使用 Hooks
去封装,如下:

或者你也可以直接放在ts
文件最外层

也是同样的效果:

defineComponent + JSX/TSX
可能会有人觉得 h
写起来很麻烦,嵌套太多的话写起来会很难受,那我们其实也可以用JSX/TSX
去替代它
同样你也可以将多个组件以JSX/TSX
的形式,维护在同一个tsx
文件中
pnpm i @vitejs/plugin-vue-jsx -D
安装完毕后,需要在 vite.config.ts
中去进行插件配置


配置完就可以写 TSX 啦!!!

同样你也可以写在外层(这里就不写了,同理)
也是同样的效果:

Vue Macros 组件 API
Vue Macros
里的特性暂时还不是正式版特性,但是以后有很大概率会成为正式版特性
defineRender + JSX/TSX
文档地址:https://vue-macros.dev/zh-CN/macros/define-render.html#definerender
defineRender
跟 defineComponent
的区别在于,defineRender
只需要关心最终的DOM结构,不需要管状态的维护

setupSFC + JSX/TSX
文档地址:https://vue-macros.dev/zh-CN/macros/setup-sfc.html#setupsfc
想使用 setupSFC
的特性,需要建一个.setup.tsx/.setup.jsx
文件,跟普通的 tsx/jsx
文件相比,每次引入.setup.tsx/.setup.jsx
这个文件,都是一个新的组件实例,状态并不会共享

setupComponent + JSX/TSX
文档地址:https://vue-macros.dev/zh-CN/macros/setup-component.html#setupcomponent
setupComponent
适合用来管理多组件,可以把多个紧密联系或共用的组件,通过setupComponent
写在同一个文件或 Hooks 里
setupComponent
中可以使用setup
的语法去写逻辑,写起来比defineComponent
简洁很多

同理,你想写在文件外层也行~这里就不具体写了
Vine

这个库的作用就是:让 Vue 组件能通过函数式来定义
举个例子,我们在平时写一个组件的时候,会通过模板的方式去定义

但是在使用了 Vue-Vine
这个库之后,可以使用函数式的方式去定义

翻看了一下Vue-Vine
的官方文档,总结出Vue-Vine
这个库的初衷是:
-
想要做到像 React JSX 那样的组件定义方式
-
可以在同个文件里定义多个组件
-
使得逻辑更加聚合,提高开发效率
总结
Vue 的组件有很多写法,合适的场景选择合适的写法,才能更好地提高开发效率~而不是死定硬背