Vue 3 + TypeScript 및 Augmenting-Types-for-Use-with-Plugins에 대한 질문
Sep 29 2020
Vue3 및 TypeScript를 사용하여 유형 확대를 구현하는 방법에 대한 작업 예제를 아는 사람이 있습니까? 나는 Vue3에서 성공하지 못한 채 Vue2 문서를 따르려고 노력하고 있으며 결과없이 지난 3 시간 동안 검색했습니다.
모듈 의 Vue객체 vue-class-component가 작동하려면 증강되어야하는 것 같지만 어떻게?
내 구현은 다음과 유사합니다.
어떤 충고?
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");
답변
A.Terra Jan 19 2021 at 03:25
내가 이해 vue-class-component하는 바는 아직 Vue 3을 완전히 지원하지 않습니다. 그들은 여전히 도서관에서 수정을 논의 하고 있습니다. 따라서 아래 예제가 작동하는지 모르겠지만 이것이 플러그인 유형을 늘리기 위해 수행 한 작업입니다.
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>