vue3 <script setup> 设置 Name 最佳实践

7,060 阅读2分钟

为什么要设置 Name 呢? 哪种 cases 需要? vue2 怎么使用的? vue3 下怎么使用? 社区里有没有好的 plugins 供我们选择? 最佳实践是什么? 下面我们按照时间顺序一个个来看。

vue2 (options api) name attr

按照官网的解释是这样的:

允许组件模板递归地调用自身。指定 name 选项的另一个好处是便于调试。有名字的组件有更友好的警告信息。另外,当在有 vue-devtools,未命名组件将显示成 <AnonymousComponent>,这很没有语义。通过提供 name 选项,可以获得更有语义信息的组件树。enter details

简而言之,设置name 有如下用途:

  1. 允许组件模板递归地调用自身,这事只能通过 name 来实现组件调用自身;
  2. <keep-alive> 组件缓存时用作 includeexclude 的值;
  3. vue-devtools 拥有更有语义信息的组件树;

vue3 (composition api) name attr

细心阅读官网的同学,会发现这个属性在 vue3 里面并没有消失,而是被移至到杂项里面去了,并且关于用途没有变化。那是不是说 Vue2vue3 使用方法一致呢?

选项式 API > 选项 > 杂项 > name. enter details

还真不是,具体来说,你不用在每个组件里面显式地声明 name, 因为 vue3 SFCs 会自动根据你的文件名去推断 name

Vue 3 SFCs automatically infers the component's name from the component's filename 

注意,这是有限定的情况的,具体请看 details.

那么,什么情况下仍然要使用呢? 答案便是:<keep-alive>。 具体请看文档解释:

In most cases, explicit name declaration is not needed. The only cases where you do need it is when you need the name for <keep-alive> inclusion / exclusion or direct inspection of the component's options. enter details

要知道,在 vue3 早期,怎么使用 name 似乎不是问题,比如:

<script lang="ts">
import { defineComponent} from 'vue';
export default defineComponent({
  name: 'test'
})
</script>

但是如果使用 <script setup> 语法糖,又该怎么设置 name 呢? 好纠结~

其实,vue3 rfcs 已经给了解决方案,单独写一个 script block。如下:

<script>
  export default {
    name: 'CustomName',
    inheritAttrs: false,
    customOptions: {}
  }
</script>

<script setup>
  // script setup logic
</script>

详情请看:enter details

Community plugins

拥有极客精神的人,会觉得这样写法不够优雅,所以社区就有了这样的方案,目前找到的就两个:

vbenjs 提供的 vite-plugin-vue-setup-extendElemenet Plus 小组成员提供的 unplugin-vue-define-options。 但是大家伙也不要太开心,目前这两种方案都有问题。

vite-plugin-vue-setup-extend: 存在调试断点错乱问题,目前这个问题作者还没有解决掉。 sourcemap is broken

unplugin-vue-define-options: webpack 打包生产环境后,会触发这样的报错信息: error in production:defineOptions is not defined。作者的回复是需要等上游解决。如果你选择其他打包工具,倒是可以一试。

插件地址:

vite-plugin-vue-setup-extend

unplugin-vue-define-options

总结

  • vue3 不用显式声明 name 属性;
  • <keep-alive> 缓存组件需要单独的写一个 script block

题图摄影: Caleb Martin | 图片协议:Unsplash License

参考链接: