vue.js - 如何在 Nuxt TypeScript 中创建自己的类型?
当我在 Nuxt 中使用 $_app 时,它说 $_app 在 this 上不存在。我想在 Nuxt 类型中将 $_app 包含为我自己的类型。我尝试了这个:
import Vue from "vue"
interface AppMixin {
user: any
}
declare module "vue/types/vue" {
interface Vue {
$_app: AppMixin
}
}
我不知道这是否正确。我甚至不知道把这段代码导入到哪里。请帮帮我。
答案#1
以下是确保其正常工作的步骤。
假设你需要提供具有 AppMixin 类型的 $_app:
/**
* Extends interfaces in Vue.js
*/
import Vue from "vue"
interface AppMixin {
user: string
}
declare module "vue/types/vue" {
interface Vue {
$_app: AppMixin
}
}
然后,你需要正确地命名这个文件:vue.d.ts,并将其放在 tsconfig.json 中 include 所包括的路径中。
我通常会在项目目录中创建 shims/ 子文件夹,如下所示:https://github.com/wemake-services/wemake-vue-template/tree/master/template/client/shims
并像这样正确配置它: https://github.com/wemake-services/wemake-vue-template/blob/master/template/tsconfig.json#L43
如果操作正确,你在 vue 组件中对 this.$_app.user 的调用将显示为 string 类型。
文档
- TypeScript 中的声明文件:https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html
Vue实例扩展示例: https://github.com/vuejs/vuex/blob/dev/types/vue.d.ts
