【问题标题】:Augmenting vue.js in typescript在 typescript 中增强 vue.js
【发布时间】:2018-06-18 12:37:31
【问题描述】:

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

我在./Definitions 下创建了一个文件vue.d.ts(相对于我的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。

我该如何正确操作?

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    假设你的项目有tsconfig.json,你应该设置compilerOptions

    {
        "compilerOptions": {
    
            "baseUrl": ".",
    
            // other options go here
    
            "typeRoots": [
                "./node_modules/@types",
                "./typings"
            ]
        }
    }
    

    完成后,创建相对于tsconfig.jsontypings/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 包装的一部分发货。如果你这样做,那么你应该删除那些。

    【讨论】:

    • 不幸的是不起作用。但我认为我有一些设置问题 - 你是对的,绑定是在 node_modules/vue 中提供的,但是如果我删除 node_modules/@types/vue,我的构建过程将停止工作。明天我会努力多看的
    • 这肯定是正确的答案。我已经清理了所有东西,然后又做了一次。然后我将vue-resource 添加到我的index.d.ts 扩充中,一切都开始工作了。不知道为什么一开始没有。我的 VS 仍然看不到绑定,但我想我会找到解决此问题的方法。谢谢
    猜你喜欢
    • 2019-10-06
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2018-04-05
    • 2018-03-26
    • 2021-10-26
    • 2017-12-07
    • 2019-08-15
    相关资源
    最近更新 更多