妙才

V1

2023/05/13阅读:17主题:凝夜紫

vue3.3 快讯

大家好,现在是 2023 年 5 月 13 日上午。不知道大家有没有注意到,前天Vue发布了3.3版本。我今天才看了一下,新的一些特性非常有用,因此想在这里给还没看过的开发者朋友稍微介绍一下最新的特性和使用案例。

“This release is focused on developer experience improvements” - 此版本主要专注开发人员的体验提升

总结

“献给时间紧急的朋友 🚀”

Vue 3.3 已发布,改进了开发人员体验、新语法和宏以及对 TypeScript 的改进。该版本包括通用组件、定义插槽和emit类型、定义组件选项以及响应式props解构和定义模型语法糖等实验性功能。该版本还包括弃用 Reactivity Transform。新宏之一,defineOptions,用于定义 Options API 选项,可用于定义除 props、emits、expose 和 slot 之外的任何选项。另一个新功能是 hoistStatic,它通过将常量声明提升到顶层来优化 SFC 编译器。最后,defineModel 是一个新的语法糖宏,用于定义双向绑定 props。

单文件组件类型导入

了解React开发的朋友可能在接触Vue3.2+TypeScript时对于单文件组件无法导入外部 TypeScript 类型而感到困惑和遗憾,其原因在于:

This is because Vue needs to be able to analyze the properties on the props interface in order to generate corresponding runtime options.

Vue 需要能够分析 props 接口上的属性,以便生成相应的运行时选项。框架底层的限制让开发者只能在定义DefinePropsdefineEmits的时候使用本地 TypeScript type 或 interface。

3.3 版本终于解决了这个问题(开发团队在 Github issue 里曾承诺会尽快解决这个问题,他们做到了),我们可以从外部导入 TypeScript 类型了:

<script setup lang="ts">
import type { Props } from './foo'

// imported + intersection type
defineProps<Props & { extraProp?: string }>()
</script>

除此之外,还可以从第三方的包导入其 TypeScript 类型或接口,亦或是引用全局类型描述文件".d.ts"内的类型。例如:

import type { Props } from 'some-package'
defineProps<Props>()

但需要注意的是,开发者不能在 props 类型中使用条件类型:

import type { Props } from './foo'
// will throw a compiler error
defineProps<Props extends object ? Props : {}>()

究其原因,还是因为这个特性是基于AST解析的,而非TypeScript的支持。

泛型组件(Generic Component)

直接看代码:

<script setup lang="ts" generic="T">
defineProps<{
  items: T[]
  selected: T
}>()
</script>

亦或是在泛型定义的时候继承内置或从第三方导入的类型:

<script setup lang="ts" generic="T extends MyItem">
  interface MyItem {
    name: string;
    foo: number
  }

  defineProps<{
    list: T[],
    modelValue?: T
  }>
</script>

使用泛型组件时,要注意更新volarvue-tsc,在调用组件时传参将会变得更加灵活。

诚然,这个泛型组件笔者没有写过,对此也不够了解,十分抱歉。如果你对此很有兴趣,推荐看看讨论区:Generic component enhancements on \`

分类:

前端

标签:

前端

作者介绍

妙才
V1