簡體   English   中英

如何使用帶有組合的 Vue 2 鍵入提示 vue 組件方法 API

[英]How to type hint a vue component method using Vue 2 with Composition API

我有兩個組件<Modal><App> ,我想調用 Modal 組件的方法。 添加@ts-ignore時代碼有效,但 TypeScript 正在抱怨。 我正在使用 Vue2 和組合 API。

簡化示例(我省略了應用程序初始化):

模態.vue

<template>
   <div ref="modalEl">I'm the modal<slot></slot></div>
</template>
<script lang="ts">
import {defineComponent, onMounted, ref} from '@vue/composition-api';
import Modal from 'bootstrap/js/dist/modal';

export default defineComponent({
    setup(props) {
       const modalEl = ref<Element | string>('');
       let modal: Modal;

       onMounted(() => {
          modal = new Modal(modalEl.value);
       });

       const show = () => modal.show();

       return {
          modalEl,
          show,
       } 
    }
});
</script>

App.vue

<template>
   <div>
       <Modal ref="modalSave">I'm modal content</Modal>
       <button @click="showModal">show modal</button>
   </div>
</template>
<script lang="ts">
import {ref,defineComponent} from '@vue/composition-api';
import Modal from 'Modal.vue';
export default defineComponent({
  components: {
      Modal
  },
  setup(props) {
      const modalSave = ref<InstanceType<typeof Modal> | null>(null);
      const showModal = () => modalSave.value?.show();

      return {
          modalSave,
          showModal
      }
  }
});

</script>

如前所述,它可以工作,我什至可以在 PhpStorm 中完成代碼。 但是當我編譯時出現錯誤:

App.vue.ts(115,24) TS2339 中的錯誤:屬性“show”在類型“{readonly $el: Element; 只讀 $options: { data?: DefaultData | 不明確的; 道具?:字符串[] | { [x: 字符串]: 道具 | { 類型?:道具 | 道具[] | 不明確的; 需要嗎?:boolean | 不明確的; 默認值?:任何; 驗證器?: ((value: any) => boolean) | 不明確的; } | 道具<...>[]; } | 不明確的; ... 35 更多...'。

有誰知道如何在不添加ts-ignore情況下讓 TypeScript 快樂?

您將需要使用defineExpose ( docs ):

<!-- MyModal.vue -->
<script setup lang="ts">
<template>
   <div ref="modalEl">I'm the modal<slot></slot></div>
</template>
<script lang="ts">
import {defineComponent, onMounted, ref} from '@vue/composition-api';
import Modal from 'bootstrap/js/dist/modal';

export default defineComponent({
    setup(props) {
       const modalEl = ref<Element | string>('');

       onMounted(() => {
          modal = new Modal(modalEl.value);
       });

       const show = () => modal.show();

       defineExpose({ show }); 👈

       return {
          modalEl,
          show,
       } 
    }
});
</script>
</script>

我現在可以通過將其放入 *.d.ts 文件中來使用(全局)擴充來解決它。 這可能不是最好的解決方案,但由於在應用程序升級到 vue3 之前它只是暫時的,因此它似乎是一個簡單的解決方案,無需大量重寫:

declare module 'vue/types/vue' {
    interface Vue {
        show: () => void
    }
}

export {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM