vue3.0+typescript 扩展全局自定义属性接口

6,002 阅读1分钟
// vue3.0+ts this.$axios中报错, 按照vue2.*中扩展合并'vue/types/vue' 模块失效
Property '$axios' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, Record<string, any>, Readonly<{}>, ComponentOptionsBase<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, Record<...>, string>>'.Vetur(2339)
// 下面是在vue3.0定义源文件找到的一段说明注释
/**
 * Custom properties added to component instances in any way and can be accessed through `this`
 *
 * @example
 * Here is an example of adding a property `$router` to every component instance:
 * ```ts
 * import { createApp } from 'vue'
 * import { Router, createRouter } from 'vue-router'
 *
 * declare module '@vue/runtime-core' {
 *   interface ComponentCustomProperties {
 *     $router: Router
 *   }
 * }
 *
 * // effectively adding the router to every component instance
 * const app = createApp({})
 * const router = createRouter()
 * app.config.globalProperties.$router = router
 *
 * const vm = app.mount('#app')
 * // we can access the router from the instance
 * vm.$router.push('/')
 * ```
 */
}
// 举例:下面是axios在vue3.0+ts中具体定义方法
import '@vue/runtime-core'
import { AxiosInstance } from "axios";

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}