有谁知道如何使用 Vue3 和 TypeScript 实现类型增强的工作示例?我一直在尝试遵循 Vue2 文档,在 Vue3 中使用相同的内容,但没有成功,并且在过去 3 个小时的搜索中没有任何结果。
看来Vue
对象在vue-class-component
模块应该被增强才能工作,但是如何呢?
我的实现类似于以下内容:
有什么建议吗?
https://v2.vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins
import { App, Plugin } from "vue";
export interface IHelloModule {
sayHello: (name: string) => string;
}
export const helloPlugin: Plugin = (app: App, options) => {
const helloModule:IHelloModule = {
sayHello: function(name: string) {
return `Hello ${name}`;
}
};
app.provide("$hello", helloModule);
};
import { Vue } from 'vue-class-component';
import { IHelloModule } from "@/hello";
declare module "vue/types/vue" {
interface Vue {
$hello: IHelloModule;
}
}
declare module "vue/types/vue" {
interface VueConstructor {
$auth: IHelloModule;
}
}
<template>
<div class="home">
.....
</div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
@Options({
components: {
},
})
export default class Home extends Vue {
mounted() {
console.log(this.$hello.sayHello("World"))
^^^^^^^^^^^^^^^^^^^^^^^^^^
Neither TS nor vue-cli recognize this
}
}
</script>
import { createApp } from "vue";
import App from "./App.vue";
import { helloPlugin } from "./hello";
import router from "./router";
createApp(App)
.use(router, helloPlugin)
.mount("#app");