Vue 3 defineEmits 打破了defineProps 类型

简单J

我正在使用 Vue 3 和 TS 4.4。我有一个组件,它用defineProps. 当我添加对 的调用时defineEmits,VS Code 开始告诉我props组件模板中不存在我的变量。这是源代码:

<script setup lang="ts">
import { defineProps, defineEmits, VueElement, defineComponent } from "vue";

const emit = defineEmits<{
  "update:checked": boolean;
}>();

const props = defineProps<{
  label?: VueElement | string;
  checked?: boolean;
}>();
</script>

<template>
  <label>
    <input
      type="checkbox"
      :checked="props.checked"
      @change="(event) => emit('update:checked', (event.target as any)?.checked)"
    />
    {{ props.label }}
  </label>
</template>

还有一些屏幕截图可以更好地展示我在 VS Code 中看到的内容。这是添加后defineEmits

VS 代码 TS 错误

这是没有defineEmits

没有 TS 错误的 VS 代码

为道具和发射定义类型的正确方法是什么?

托尼19

defineEmits<T>()一般的参数本质上是一个打字稿接口仅定义功能,其中接收特定事件名称和可选参数:

interface Emits {
  (e: __EVENT1_NAME__ [, arg1: __ARG1_TYPE__ [, arg2: __ARG2_TYPE__]]...): void
  (e: __EVENT2_NAME__ [, arg1: __ARG1_TYPE__ [, arg2: __ARG2_TYPE__]]...): void
}

例子:

// as inline type
const emits = defineEmits<{
  (eventName: 'hover', hovering: boolean): void
  (eventName: 'changed', newValue: number, id: string): void
}>()
// as interface
interface Emits {
  (eventName: 'hover', hovering: boolean): void
  (eventName: 'changed', newValue: number, id: string): void
}
const emits = defineEmits<Emits>()
// as type alias
type Emits = {
  (eventName: 'hover', hovering: boolean): void
  (eventName: 'changed', newValue: number, id: string): void
}
const emits = defineEmits<Emits>()

对于您的update:checked事件,代码应类似于以下内容:

// as inline type
const emits = defineEmits<{
  (e: 'update:checked', checked: boolean): void
}>()
// as interface
interface Emits {
  (e: 'update:checked', checked: boolean): void
}
const emits = defineEmits<Emits>()
// as type alias
type Emits = {
  (e: 'update:checked', checked: boolean): void
}
const emits = defineEmits<Emits>()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

枚举类型的 TypeConverter 属性打破了该类型的依赖属性

TypeScript 可选属性打破了函数参数的类型强制

我是否打破了Java的局部变量类型推断?

Doc类型打破了我的CSS,为什么?

Vue模板中的地址标签打破了皮棉

CCSM在11.10上打破了我的Unity 3D

VS 2012 Update 3打破了我的VS

为什么会编译?代码似乎打破了对类型参数的约束

新的语言功能打破了脚手架-无法获得DbContext的反射类型

为什么 Vue 现在有额外的 <Root /> ?它完全打破了 this.$root

将Vue 2迁移到Vue 3,类型错误:Vue不是构造函数

Vue 3 Typescript类组件-类型'typeof import(... / node_modules / vue / dist / vue“)'不是构造函数类型

与Vue 3插件一起使用的增强类型

什么是 Vue 3 组合 API 定义方法的类型安全方式

Vue3具有强类型的Axios请求

如何设置主Vue 3“app”变量的“类型”

数据类型赋值 TS+Vue3

哪个宝石打破了Rails application.css.scss的错误参数数3换2

错误TS2339:类型“ typeof Observable”上不存在属性“ timer”。'switchMap'和'takeUntil'打破了流程

Vue.js 3:使用自定义类型验证道具类型

Vue 3,未捕获的类型错误:Vue.use 不是函数

JacksonFeature打破了JsonIgnoreProperties

mapcat打破了懒惰

Goroutines打破了程序

Vue:无效的prop:类型

类型错误:无法读取未定义的属性“created”,错误“Vue”未定义 Vue.js 3

Vue 3 + Typescript:在单个文件组件中进行类型检查道具

如何使用 ts 在 vue3 中将 ref 数据定义为类类型

Vue.js 3和typescript:类型“ ComponentPublicInstance”上不存在属性“ $ store”