vue-cli3 + ts 通过Vue.prototype绑定的属性方法,能够调用到,但是编译报错

//main.ts 里面

import * as api from '@/api' //接口方法
Vue.prototype.$api = api
App.vue 里面

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
@Component
export default class App extends Vue {
  public created() {
    this.$api.getUserInfo().then(res => {
      console.log(res, 'res')
    }).catch(err => {
      console.log(err, 'err')
    })
  }
  public mounted() {}
}
</script>

我在App.vue里面调用this.$api.xxx能够正常调用到api里面的方法,但是编译的时候会报错警告
Property '$api' does not exist on type 'App'.
请问这个怎么回事啊?

阅读 7.6k
2 个回答

vue文档上有

// 1. 确保在声明补充的类型之前导入 'vue'
import Vue from 'vue'

// 2. 定制一个文件,设置你想要补充的类型
//    在 types/vue.d.ts 里 Vue 有构造函数类型
declare module 'vue/types/vue' {
// 3. 声明为 Vue 补充的东西
  interface Vue {
    $myProperty: string
  }
}
import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $api: any
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题