有没有人知道如何在Vue3和TypeScript中实现类型增强的可行示例?我一直在尝试按照Vue2文档的步骤来实现,但是没有成功,并且花了过去三个小时搜索也没有找到任何结果。
似乎应该通过vue-class-component
模块中的Vue
对象进行增强处理,但是如何实现呢?
我的实现方式与以下示例类似:
有什么建议吗?
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");
HelloWorld
组件的代码如下:class HelloWorld extends Vue { msg!: string; }
。在组件内部,我定义了mounted
函数,并且编译器报错说$
变量(从你的示例中是$hello
)在this
关键字上不存在。我对 Vue 不是很熟悉,所以不确定缺少什么,也没有找到太多关于 Vue + TS + 插件的资源。 - Rodrigo Gomez-Palacio