首页 > 解决方案 > 如何使用 Typescript 在 vuejs 中创建功能组件

问题描述

我想用打字稿在 vuejs 中创建一个功能组件。但是,我不确定如何设置通用部分以便我可以访问我的道具。到目前为止我有这个:

import Vue, { FunctionalComponentOptions } from 'vue';

export default Vue.component<FunctionalComponentOptions>('MyWrapper', {
    functional: true,
    render: (createElement, context) => {

        if (context.props['flagSet']) {
            console.log('flagset');
        }

        return createElement('div', context.data, context.children);
    }
});

我得到的 context.props 行的错误是 Element implicitly has an 'any' type because type 'FunctionalComponentOptions<Record<string, any>, PropsDefinition<Record<string, any>>>' has no index signature.

我不确定如何解决。

标签: typescriptvuejs2

解决方案


使上述代码工作的正确方法是传入一个描述 props 的接口。

interface IProps {
    flagSet: string;
}

export default Vue.component<IProps>

回顾最初的问题,我不确定为什么要尝试将FunctionalComponentOptions其作为类型参数插入。我责怪深夜的编码会议。:)


推荐阅读