vue3.0使用TypeScript 如何拓展一个方法并且this可以访问,不报错?

那么在近期更新的vue3.0且使用ts的项目中,我们该怎样拓展一个方法呢?
vue3.0使用typescript重构,而拓展方法的方式也更加规范

main.ts中

import { createApp,defineComponent } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

const instance = createApp(App);

instance.use(function (vue) { 
  vue.config.globalProperties.$myProperty = "我是渣男"
})
instance.use(router);
instance.use(store);
instance.mount("#app")

报错了,ts告诉我们$myProperty这个属性不在ComponentPublicInstance这个类型上面,我们来看一下解决办法:

新建index.d.ts文件

```javascript
import { createApp } from 'vue'
import { Router, createRouter } from 'vue-router'
declare module "@vue/runtime-core" { 
  interface ComponentCustomProperties { 
    $myProperty: string;
  }
}

3.那么在setUp中如何使用全局的方法呢?
首先我们使用到一个3.0的api getCurrentInstance()
这个方法返回的就是当前组件的实例实际用法

<script lang="ts">
import {
  ComponentInternalInstance,
  defineComponent,
  getCurrentInstance,
} from 'vue';

export default defineComponent({
  name: 'HelloWorld',
  setup() {
    const {proxy} = getCurrentInstance() as ComponentInternalInstance;
    proxy?.$myProperty;
  },
  props: {
    msg: String,
  },
});
</script>

或者:

const internalInstance = getCurrentInstance() as ComponentInternalInstance
internalInstance.appContext.config.globalProperties.$myProperty

说明一下为什么要用as ,因为vue的源码里面,getCurrentInstance()这个方法返回的是
ComponentInternamInstance | null

或者
不用解构赋值,用?.也可以

    const proxy = getCurrentInstance()?.proxy;
    proxy?.$myProperty

注意,拓展完类型之后一定要重启,要不然会报错!!!

但是使用以上方法使用后出现import语句全部报错,解决方法:

declare module "@vue/runtime-core" { 
  interface ComponentCustomProperties { 
    $myProperty: string;
  }
}

不要放在.d.ts中,放在 main.ts中就不会报错

原文:https://www.jianshu.com/p/12faae13496d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值