Lanzamiento de Vue 3.3

Este artículo está traducido

Dirección original: Anunciando el lanzamiento de Vue 3.3 | The Vue Point (vuejs.org)

¡Hoy nos complace anunciar el lanzamiento de Vue 3.3 "Rurouni Kenshin"!

Esta versión se centra en las mejoras de la experiencia del desarrollador, específicamente en el uso de SFC de TypeScript <script setup>. Junto con  la versión 1.6 de Vue Language Tools (anteriormente Volar), hemos abordado muchos problemas antiguos al usar Vue con TypeScript.

Esta publicación proporciona una descripción general de las funciones destacadas en 3.3. Para obtener una lista completa de cambios, consulte  el registro de cambios completo en GitHub .


actualización de dependencia

Al actualizar a 3.3, se recomienda actualizar también las siguientes dependencias:

  • Volar / vue-tsc@^1.6.4
  • invitar@^4.3.5
  • @vitejs/plugin-vue@^4.2.0
  • vue-loader@^17.1.0 (si usa webpack o vue-cli)

Tabla de contenido

<script setup>+ mecanografiado DX mejoras

Compatibilidad con importaciones de tipos y tipos complejos en macros

Anteriormente, los tipos utilizados en las posiciones de los parámetros de tipo definePropsy estaban limitados a los tipos locales, y solo se admitían los literales de tipo y las interfaces. defineEmitsEsto se debe a que Vue necesita poder analizar las propiedades en la interfaz de accesorios para generar las opciones de tiempo de ejecución correspondientes.

Esta limitación ahora se resuelve en 3.3. El compilador ahora puede resolver tipos importados y admite un conjunto limitado de tipos complejos:

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

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

请注意,复杂类型支持是基于 AST 的,因此不是 100% 全面的。不支持一些需要实际类型分析的复杂类型,例如条件类型。您可以将条件类型用于单个 props 的类型,但不能对整个 props 对象使用。

泛型组件

使用 <script setup> 的组件现在可以通过 generic 属性接受泛型类型参数:

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

generic 的值与 TypeScript 中的<...>参数列表完全相同。例如,可以使用多个参数、extends 约束、默认类型和引用导入的类型:

<script setup lang="ts" generic="T extends string | number, U extends Item">
import type { Item } from './types'
defineProps<{
  id: T
  list: U[]
}>()
</script>

此功能以前需要明确的选择加入,但现在在最新版本的 volar/vue-tsc 中默认启用。

更符合人体工程学defineEmits

以前,defineEmits 的类型参数仅支持调用签名语法:

// BEFORE
const emit = defineEmits<{
  (e: 'foo', id: number): void
  (e: 'bar', name: string, ...rest: any[]): void
}>()

该类型与 emit 的返回类型匹配,但编写起来有点冗长和笨拙。3.3 引入了一种更符合人体工程学的用类型声明发出的方式:

// AFTER
const emit = defineEmits<{
  foo: [id: number]
  bar: [name: string, ...rest: any[]]
}>()

在类型文本中,键是事件名称,值是指定其他参数的数组类型。尽管不是必需的,但您可以使用标记的元组元素来实现显式性,如上例所示。

仍支持以前的函数调用签名语法。

类型化插槽defineSlots

新的宏 defineSlots 可用于声明预期的插槽及其各自的预期插槽道具:

<script setup lang="ts">
defineSlots<{
  default?: (props: { msg: string }) => any
  item?: (props: { id: number }) => any
}>()
</script>

defineSlots()只接受类型参数,不接受运行时参数。类型参数应为类型文本,其中属性键是槽名称,值是槽函数。函数的第一个参数是插槽期望接收的道具,其类型将用于模板中的槽道具。defineSlots 的返回值与从 useSlots 返回的插槽对象相同。

当前的一些限制:

  • 所需的插槽检查尚未在 volar / vue-tsc 中实现。
  • slot 函数返回类型目前被忽略,但我们将来可能会利用它来检查槽内容。

defineComponent 还有一个相应的 slots 选项。这两个 API 都没有运行时影响,纯粹用作 IDE 和 .vue-tsc

实验性功能

Reactive 解构(Reactive Props Destructure)

以前是现在放弃的反应性变换的一部分,反应式道具解构已被拆分为一个单独的功能。

该功能允许解构道具保持反应性,并提供一种更符合人体工程学的方式来声明道具默认值:

<script setup>
import { watchEffect } from 'vue'

const { msg = 'hello' } = defineProps(['msg'])

watchEffect(() => {
  // accessing `msg` in watchers and computed getters
  // tracks it as a dependency, just like accessing `props.msg`
  console.log(`msg is: ${msg}`)
})
</script>

<template>{{ msg }}</template>

此功能是实验性的,需要明确选择加入。

defineModel

以前,对于支持 v-model 双向绑定的组件,它需要 (1) 声明一个 prop 和 (2) 在打算更新 prop 时发出相应的update:propName事件:

<!-- BEFORE -->
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
console.log(props.modelValue)

function onInput(e) {
  emit('update:modelValue', e.target.value)
}
</script>

<template>
  <input :value="modelValue" @input="onInput" />
</template>

3.3 简化了新宏的使用。defineModel 宏会自动注册一个 prop,并返回一个可以直接变异的 ref:

<!-- AFTER -->
<script setup>
const modelValue = defineModel()
console.log(modelValue.value)
</script>

<template>
  <input v-model="modelValue" />
</template>

此功能是实验性的,需要明确选择加入。

其他值得注意的功能

defineOptions

新的宏defineOptions允许直接在 <script setup> 中声明组件选项,而无需单独的块:

<script setup>
defineOptions({ inheritAttrs: false })
</script>

Better Getter Support with toRef and toValue

toRef已得到增强,支持将values / getter /existing refs 规范化为引用:

// equivalent to ref(1)
toRef(1)
// creates a readonly ref that calls the getter on .value access
toRef(() => props.foo)
// returns existing refs as-is
toRef(existingRef)

toRef使用 getter 调用类似于computed ,但当 getter 只是执行属性访问而不进行昂贵的计算时,可能会更有效。

新的实用程序toValue方法提供了相反的结果,将值values/getter/refs 规范化为values :

toValue(1) //       --> 1
toValue(ref(1)) //  --> 1
toValue(() => 1) // --> 1

toValue可以在可组合项中使用,unref 以便您的可组合项可以接受 getter 作为反应式数据源:

// before: allocating unnecessary intermediate refs
useFeature(computed(() => props.foo))
useFeature(toRef(props, 'foo'))

// after: more efficient and succinct
useFeature(() => props.foo)

toReftoValue 之间的关系类似于 refunref 之间的关系,主要区别在于 getter 函数的特殊处理。

JSX 导入源支持

目前,Vue 的类型会自动注册全局 JSX 类型。这可能会导致与其他需要 JSX 类型推理的库(特别是 React)一起使用的冲突。

从 3.3 开始,Vue 支持通过 TypeScript 的 jsxImportSource 选项指定 JSX 命名空间。这允许用户根据其用例选择全局或每个文件选择加入。

为了向后兼容,3.3 仍然全局注册 JSX 命名空间 。我们计划在 3.4 中删除默认的全局注册。 如果你在 Vue 中使用 TSX,你应该在升级到 3.3 后在tsconfig.json显式添加 jsxImportSource,以避免在 3.4 中出现损坏。

维护基础设施改进

此版本基于许多维护基础架构改进,使我们能够更快地、更自信地移动:

  • 通过将类型检查与汇总版本分离并从 rollup-plugin-typescript2 更换为 rollup-plugin-esbuild,将生成速度提高 10 倍。
  • 通过从 Jest 更换为 Vitest 来加快测试速度。
  • 通过从 @microsoft/api-extractor 更换为 rollup-plugin-dts 来更快地生成类型。
  • 通过生态系统-ci进行全面的回归测试 - 在发布之前捕获主要生态系统依赖项的回归!

Según lo planeado, nuestro objetivo es comenzar a lanzar lanzamientos de funciones más pequeños y frecuentes en 2023. ¡Manténganse al tanto!

Supongo que te gusta

Origin juejin.im/post/7232115066480394300
Recomendado
Clasificación