[Vue小技巧] 全局指令类型安全

326 阅读1分钟

Vue3 文档 自定义指令 中未提及到的 注册全局指令后如何确保 类型安全

本例子代码仓库: github.com/Cyenoch/vue…

此方式同样适用于 Nuxt

定义全局指令和类型

// src/directives/identity-guard.ts

import { Directive } from "vue"

export type IdentityGuardBinding = {
  role: 'Admin' | 'User'
}

export const DirectiveIdentityGuard: Directive<HTMLElement, IdentityGuardBinding> = (el, binding) => {
    // business...
}

注册全局指令

参考

Nuxt 中 请参考 Vue Directives

// src/main.ts

import { createApp } from 'vue'
import App from './App.vue'

// 导入指令
import { DirectiveIdentityGuard } from './directives/identity-guard'

const app = createApp({}) // make v-identity-guard usable in all components

// 注册指令
app.directive('identity-guard', DirectiveIdentityGuard)

app.mount('#app')

扩展组件类型

创建/修改文件 shim-types.d.ts

// src/shim-types.d.ts

import { DirectiveIdentityGuard } from "./directives/identity-guard";

declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    vIdentityGuard: typeof DirectiveIdentityGuard
  }
}

修改 tsconfig.json 添加 shim-types.d.ts

{
  "compilerOptions": {
    // ...
    "types": [
      // ...
      "./src/shim-types.d.ts"
    ]
  }
}

效果

<HelloWorld msg="Passed the identity guard" v-identity-guard="{role: 'Admin'}" />

image.png

完事

image.png

image.png