如何处理vue-cli3+ts+element-ui 调用$message/$alert时的编译报错

使用vue-cli3新建的ts项目,按照element-ui的文档载入了element-ui,能够正常使用

但是,今天在调用$message方法时,出现了以下错误

ERROR in E:/seat-admin/src/views/seatManagement/seatManagement.vue
241:12 Property '$message' does not exist on type 'SeatManagement'.
    239 |   private removeArea (key: string): void {
    240 |     if (this.areaArray.length === 1) {
  > 241 |       this.$message('至少保留一个');
        |            ^
    242 |       return
    243 |     }
    244 |     this.areaArray = this.areaArray.filter(area => {
复制代码

错误提示说,组件实例下面没有$message这个属性,查了很多资料,发现应该是ts的声明出了问题,但是Ctrl+左键点击$message确实可以跳转到element-ui已经设置好的声明文件中 node_modules\element-ui\types\message.d.ts

export interface ElMessage {
  /** Show an info message */
  (text: string): ElMessageComponent

  /** Show message */
  (options: ElMessageOptions): ElMessageComponent

  /** Show a success message */
  success (text: string): ElMessageComponent

  /** Show a warning message */
  warning (text: string): ElMessageComponent

  /** Show an info message */
  info (text: string): ElMessageComponent

  /** Show an error message */
  error (text: string): ElMessageComponent
}

declare module 'vue/types/vue' {
  interface Vue {
  /** Used to show feedback after an activity. The difference with Notification is that the latter is often used to show a system level passive notification. */
    $message: ElMessage
  }
}
复制代码

上面的代码可以看到,element-ui本身已经将$message方法声明好了,所以怀疑是这些代码没有加载到项目中去

我查看了typescript的文档,发现对于编译配置部分有相关的说明

ts文档,看@types,typeRoots和types部分

文档上说,编译时默认拉取node_modules/@types下面的文件,额外还有typeRootstypes两个属性可以自定义配置 看下我们项目中的tsconfig文件:

{
  "compilerOptions": {
    "types": [
      "webpack-env",
      "mocha",
      "chai"
    ]
  }
}
复制代码

可以看到,设置了types属性,表示只使用以下三个位置的配置

node_modules/@types/webpack-env

node_modules/@types/mocha

node_modules/@types/chai

但是element-ui的types位置在node_modules/elememt-ui/types下面,所以试着将这个位置加入了配置中

{
  "compilerOptions": {
    "types": [
      "webpack-env",
      "mocha",
      "chai",
      "./../element-ui/types"
    ]
  }
}
复制代码

好了,编译成功!!

No type errors found
Version: typescript 3.2.4
Time: 3196ms
复制代码

你可能感兴趣的:(如何处理vue-cli3+ts+element-ui 调用$message/$alert时的编译报错)