【问题标题】:Vue 3 - Composition Api - Typescript -> type of emitVue 3 - Composition Api - Typescript -> 发射类型
【发布时间】:2021-05-31 03:10:12
【问题描述】:

我从 VUE 3 和第一次使用 Typescript 的组合 API 开始。 我有如下设置方法: setup(props: { widgetType: string; displayType: string; trigger: number }, { emit }) 现在,当我构建这个文件时,我收到错误“绑定元素'emit'隐式具有'any'类型。”。 我不知道如何解决这个问题。我尝试了来自网络的不同解决方案,但没有任何效果。 有谁能够帮我? 问候 克里斯

【问题讨论】:

  • 你是如何定义你的组件的?

标签: typescript vue.js composition


【解决方案1】:

例如正确键入组件“App”和可组合“useModal”

应用:

<script lang="ts"> 
 import {defineComponent, SetupContext, ComponentPropsOptions} from 'vue';
 import {useModal} from '@/composable/useModal';
                    
 export default defineComponent({
   name: 'App',
   setup(props: ComponentPropsOptions, {emit}: SetupContext) {
     const openModal = useModal({emit});
                    
     return {openModal};
   }
});
</script>

使用模式:

import {SetupContext} from 'vue';

interface UseModalProps {
  emit: SetupContext['emit'];
}

export function useModal({emit}: UseModalProps) {
  function openModal({title, type}: {title: string; type: string}): void {
    emit('openModal', {title, type});
  }

  return {openModal};
}

【讨论】:

    【解决方案2】:

    您需要使用defineComponent 方法定义您的组件并将正确的类型应用于道具。如果您使用的是单个文件组件,它看起来像这样

    <script lang="ts">
    import { defineComponent } from 'vue'
    export default defineComponent({
        props: {
            widgetType: {
                type: String,
                required: true
            },
            displayType: {
                type: String,
                required: true
            },
            trigger: {
                type: number,
                required: true
            }
        },
    
        setup(props, { emit }) {
    
            // Rest of your setup code here
        }
    });
    </script>
    

    【讨论】:

      【解决方案3】:

      要做一个快速的脏修复,你可以这样做:

      setup(props: { widgetType: string; displayType: string; trigger: number }, { emit }: { emit: Function | (eventName: string, payload: any) => void })
      

      但我建议您使用整个组件更新您的问题,以便我们了解问题的根本原因

      【讨论】:

        猜你喜欢
        • 2021-04-26
        • 2020-04-10
        • 1970-01-01
        • 2021-09-22
        • 2022-11-29
        • 2020-06-16
        • 2020-11-11
        • 1970-01-01
        • 2021-08-15
        相关资源
        最近更新 更多