如何动态导入组件

How to dynamically import a component

我正在尝试在 Vue 中创建一个通用表单字段,可以将其配置为使用各种不同的小部件进行输入。我想要一个输入目录,然后导入正确的目录并在我的组件中使用它。到目前为止,我什至无法让导入工作。该组件的灵感来自 React 的 Winterfell 库,它使用模式来配置表单。我将 Vue 与标准的 webpack 加载器和 JSX 一起使用。

到目前为止,这是我的简单 FieldValue 组件。我希望能够动态导入组件,例如 ./inputs/TextInput(或输入子目录中的任何其他名称)。

<script>

/* Schema format
    {
        id: 'ABCD',
        label: 'Some text',
        input: {
            type: theNameOfTheInputComponentToUse,
            options: {
                ...
            }
        }
    }
*/

var Inputs = require('./inputs');

export default {
    props: {
        schema: {
            type: Object,
            required: true
        }
    },
    render: function(h) {
        // let Input = Inputs[this.schema.input.type];
        let Input = require('./inputs/' + this.schema.input.type);
        if (!Input) {
            throw new Error('Unknown Input Type "' + this.schema.input.type + '". This component should exist in the inputs folder.');
        }

        return (
            <div class="form-group">
                <label for="{this.id}" class="col-sm-2 control-label">{this.schema.label}</label>
                <div class="col-sm-10">
                    {JSON.stringify(this.schema)}
                    <input schema={this.schema} />
                </div>
            </div>
        );
    }
};
</script>

当我尝试 运行 应用程序时,它无法编译并且我在控制台中收到以下错误:

This dependency was not found in node_modules:

* ./inputs

非常感谢任何帮助实现此工作的人!

模块导入已经在构建阶段解决,在代码实际 运行 之前,所以您遇到该错误是可以理解的。

您应该只导入所有可能的输入,然后根据 this.schema.input.type 确定使用哪一个。像这样:

const allInputs = {
  text: require('./inputs/text'),
  number: require('./inputs/number'),
}

const inputToUse = allInputs[this.schema.input.type]

在我看来你已经有了类似的东西,从 var Inputs = require('./inputs');// let Input = Inputs[this.schema.input.type];

行判断