有没有人知道应该如何用Vue3和TypeScript实现类型扩充的工作示例?我一直在尝试在Vue3中使用相同的Vue2文档,但没有成功,并且花了过去3个小时的搜索也没有任何结果。
看起来应该对vue-class-component模块中的Vue对象进行扩充才能工作,但是该怎么做呢?
我的实现类似于以下内容:
有什么建议吗?
https://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");发布于 2021-01-19 11:25:55
据我所知,vue-class-component还没有完全支持Vue 3。它们仍然是库中的discussing修改。因此,我不知道下面的例子是否适用于它,但这就是我为增强插件类型所做的工作。
hello.plugin.ts
import { App } from "vue";
export interface IHelloModule {
sayHello: (name: string) => string;
}
export default {
install: (app: App) => {
const helloModule: IHelloModule = {
sayHello: function(name: string) {
return `Hello ${name}`;
}
};
app.config.globalProperties.$hello = helloModule;
}
}
declare module "@vue/runtime-core" {
//Bind to `this` keyword
interface ComponentCustomProperties {
$hello: IHelloModule;
}
}我在插件文件中声明了类型,但您也可以在shims-vue.d.ts文件中声明它们。
main.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import Hello from "./hello.plugin";
createApp(App)
.use(router)
.use(Hello)
.mount("#app");Hello.vue
<script lang="ts">
import { defineComponent } from "vue";
const Hello = defineComponent({
mounted() {
console.log(this.$hello.sayHello("World"));
}
});
export default Hello;
</script>https://stackoverflow.com/questions/64118679
复制相似问题