那么在近期更新的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