为自定义全局指令添加类型
可以通过扩展 ComponentCustomProperties 来为使用 app.directive() 声明的全局自定义指令获取类型提示和类型检查
ts
import type { Directive } from 'vue'
export type HighlightDirective = Directive<HTMLElement, string>
declare module 'vue' {
export interface ComponentCustomProperties {
// 使用 v 作为前缀 (v-highlight)
vHighlight: HighlightDirective
}
}
export default {
mounted: (el, binding) => {
el.style.backgroundColor = binding.value
}
} satisfies HighlightDirectivets
import highlight from './directives/highlight'
// ...其它代码
const app = createApp(App)
app.directive('highlight', highlight)在组件中使用:
vue
<template>
<p v-highlight="'blue'">This sentence is important!</p>
</template>