网站搜索

typescript - 如何在 Vue 中为类属性定义类型?


根据 https://vuejs.org/guide/essentials/class-and-style.html 上的文档,Vue 中的 class 绑定可以接受字符串、数组和对象。

在设置一个组件以接受 class 属性(例如 someInnerComponentClass)时,使用哪种类型是最合适的?

如果我只传递一个字符串,这个方法是可行的,但我希望它能够像我在根元素上设置 :class="['some-class', { 'conditional-class': myFlag }]" 那样接受数组和对象:

const props = defineProps<{ class?: string }>();

我可以尝试建立自己的类型,它可以接受字符串、字符串数组、对象数组等,但我觉得已经有一个类型可以涵盖这些,我可以导入,不是吗?

我的 IDE(WebStorm)将 class 属性视为普通属性:

答案#1

我在 Vue 的核心中没有找到任何可用的类型,但我们可以使用文档中的信息来自己编写类型。它可以是:

  • string
  • Record<string, boolean>(对象语法)
  • (string | Record<string, boolean>)[](组合)

所以你可以这样做:

type Class = string | Record<string, boolean> | (string | Record<string, boolean>)[];

const props = defineProps<{ class?: Class }>();

答案#2

如果有人使用 Vue Options API 看到这个问题,

我建议使用以下打字方式

type CssClass = string | string[] | Record<string, boolean>;

捕捉你典型的 "foo bar" CSS 类

以及 Vue 绑定样式的 CSS 类是否

  • 从计算属性生成的 CSS 类字符串数组 [isActive, hasError]

  • 或一个由布尔值切换的 CSS 字符串对象 { "active": isActive, "error": hasError }

然后你可以把它插入到你的道具选项中

props: {
  cssClasses: {
    type: [Array, Object, String] as PropType<CssClass>
  }
}