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


// 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;
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM