繁体   English   中英

为 vue3 setup() arguments 正确的 typeScript 类型

[英]Correct typeScript Type for vue3 setup() arguments

我正在使用带有 typescript 的 vue3,并且我正在使用组合 API。

export default {
    setup(props, context) {
    },
};

这会引发如下错误

编译失败。

src/components/LoginForm.vue:20:11
TS7006: Parameter 'props' implicitly has an 'any' type.
    18 |
    19 | export default {
  > 20 |     setup(props, context) {
       |           ^^^^^

我知道这可以通过制作任何类型的propscontext来解决,但这会破坏 TypeScript 的目的。

VS Code intellisense 向我展示了以下类型,但我无法从这些类型中找到导出的模块。

setup?: ((this: void, props: {}, ctx: SetupContext<EmitsOptions>) => void | RenderFunction

setup function 的正确类型是什么,以及从哪里导出?

无法推断道具,因为您忘记使用defineComponent方法来创建组件。 要解决此问题并让Vue的道具成为红外线,您需要包装您在defineComponent方法中导出的整个 object。

更多关于defineComponent

示例 Vue 3 组合 API 组件的<script lang="ts">部分应如下所示:

export default defineComponent({
  name: "PersonComponent",
  props: {
    firstName: {
      type: String,
      required: true
    },
    lastName: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      required: true
    }
  },
    setup(props) {
    const firstName = props.firstName;
    const lastName = props.lastName;
    const age = props.age;
    return {
      firstName,
      lastName,
      age
    };
  }
})

在此处输入图像描述


在此处输入图像描述

对于更复杂的类型,例如接口,您需要使用Object as PropType<T>Object as PropType<IconProps> )。 更多关于PropType<T>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM