Skip to content

工具类型

INFO

此页面仅列出了一些可能需要解释其使用方式的常用工具类型。有关导出类型的完整列表,请查看源代码

PropType<T>

在定义运行时 props 时用更高阶的类型定义来标注一个 prop。

  • 示例

    import { PropType } from 'vue'
    
    interface Book {
      title: string
      author: string
      year: number
    }
    
    export default {
      props: {
        book: {
          // 提供一个比 `Object` 更具体的类型
          type: Object as PropType<Book>,
          required: true
        }
      }
    }
    
  • 参考指南 - 为组件 props 标注类型

ComponentCustomProperties

用于增强组件实例类型以支持自定义全局属性。

  • 示例

    import axios from 'axios'
    
    declare module 'vue' {
      interface ComponentCustomProperties {
        $http: typeof axios
        $translate: (key: string) => string
      }
    }
    

    TIP

    类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看类型扩充指南了解更多细节

  • 参考指南 - 扩充全局属性

ComponentCustomOptions

用来扩充组件选项类型以支持自定义选项。

  • 示例

    import { Route } from 'vue-router'
    
    declare module 'vue' {
      interface ComponentCustomOptions {
        beforeRouteEnter?(to: any, from: any, next: () => void): void
      }
    }
    

    TIP

    类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看类型扩充指南了解更多细节。

  • 参考指南 - 扩充自定义选项

ComponentCustomProps

用于扩充允许的 TSX prop,以便在 TSX 元素上使用没有在组件选项上定义过的 prop。

  • 示例

    declare module 'vue' {
      interface ComponentCustomProps {
        hello?: string
      }
    }
    
    export {}
    
    // 现在即使没有在组件选项上定义过 hello 这个 prop 也依然能通过类型检查了
    <MyComponent hello="world" />
    

    TIP

    类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看类型扩充指南了解更多细节。

CSSProperties

用于扩充在样式属性绑定上允许的值的类型。

  • 示例

允许任意自定义 CSS 属性:

declare module 'vue' {
  interface CSSProperties {
    [key: `--${string}`]: string
  }
}
<div style={ { '--bg-color': 'blue' } }>
<div :style="{ '--bg-color': 'blue' }">

TIP

类型增强必须被放置在一个模块 .ts.d.ts 文件中。查看类型增强指南了解更多细节。

参考

SFC <style> 标签支持通过 v-bind:CSS 函数来链接 CSS 值与组件状态。这允许在没有类型扩充的情况下自定义属性。

工具类型 has loaded