繁体   English   中英

在 typescript 中增强 vue.js

[英]Augmenting vue.js in typescript

我正在尝试通过额外的映射来增强 vue js。 我正在关注这个: https ://v2.vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins

我在vue.d.ts ./Definitions相对于我的main.ts )我在main.ts中引用了它:

require("./Definitions/vue.d.ts");

vue.d.ts我放了:

 // 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
    // 3. Declare augmentation for Vue
    interface Vue {
        $myProperty: string
    }
}

但是这个:

var vm = new Vue()
console.log(vm.$myProperty);

不解决。

我尝试将declare module 'vue/types/vue'更改为declare module 'vue' 这给了我一个错误: "Cannot augument module 'vue' because it resolves to a non-module entity"

原始的 vue 类型位于{projectDir}\node_modules\@types\vue\index.d.ts 我正在使用 webpack。

我该如何正确地做到这一点?

假设您的项目有tsconfig.json ,您应该设置以下compilerOptions

{
    "compilerOptions": {

        "baseUrl": ".",

        // other options go here

        "typeRoots": [
            "./node_modules/@types",
            "./typings"
        ]
    }
}

完成此操作后,创建相对于tsconfig.json和您提到的路径的 typings typings/vue文件夹。 typings/vue文件夹中,创建index.d.ts文件。 通常,您的声明文件如下所示:

import Vue from 'vue';
import { AppStore } from '../../src/store/store';

declare module 'vue/types/vue' {
    // Global properties can be declared
    // on the `VueConstructor` interface
    interface VueConstructor {
        // some more augmentation
    }

    // Properties added to Vue interface are added to Vue instance
    interface Vue {
        store$: AppStore;
    }
}

比您尝试使用的方法更喜欢这种方法,因为导入类型文件并不能很好地扩展。

此外,使用最新的 Vue.js,您不需要node_modules/@types/vue声明。 它们作为官方node_modules/vue包的一部分提供。 如果你这样做,那么你应该删除那些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM