【问题标题】:How to dynamically import a component如何动态导入组件
【发布时间】:2017-05-31 22:05:17
【问题描述】:

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

到目前为止,这是我的简单 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

非常感谢任何帮助完成这项工作!

【问题讨论】:

    标签: vue-component vue.js


    【解决方案1】:

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

    您应该只导入所有可能的输入,然后根据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]; 的行来看,您似乎已经有了类似的东西

    【讨论】:

    • 谢谢。这适用于我需要提前注册输入目录中的所有组件的警告。使用 require('./inputs') 仍然会导致构建错误。我使用 标签而不是 JSX 将其更改为使用动态组件,它似乎正在工作。
    • 我相信require('./inputs) 不是从目录中导入所有内容的自动方式,而是默认尝试导入./inputs/index.js。因此,您需要确保该文件存在并导入所有其他文件。
    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 2021-10-04
    • 2013-02-24
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2019-02-03
    相关资源
    最近更新 更多