vuejs-异步和动态组件

时间:2018-11-07 11:10:30

标签: vuejs2

我要实现的是将vuejs的“异步组件”及其“动态组件”(https://vuejs.org/v2/guide/components-dynamic-async.html)结合起来,以获得使用动态组件的灵活方式。

比方说,我有以下组成部分:

<template>
    <div>
       some stuff..
       <component :is="type"></component>
       some stuff...
    </div>
</template>

<script>
    export default {
        name: "mycomponent",
        props: {
            type: {}
        }
    }
</script>

我会这样使用它:

<mycomponent type="myinput"></mycomponent>

要使其正常运行,我需要将myinput组件加载到mycomponent中,然后我将通过aync进行操作:

components: {
    MyInput: () => import("./myinput")
}

那行得通!

现在的问题是,我想使其动态并像这样使用它:

<mycomponent type="myinput"></mycomponent>
<mycomponent type="myselect"></mycomponent>
<mycomponent type="mytextarea"></mycomponent>
...

要启动并运行它,我需要将所有这些组件导入mycomponent中,这显然不是一个好主意。全局导入也是可行的,而不是可行的方法。

这只是一个示例,但真正的用例是从api获取type数组并使用它动态呈现表单。

1 个答案:

答案 0 :(得分:0)

所以我想出了我无法尝试的方法。

为了简单起见,您可以为不同类型的输入提供一个组件,为它们全都加上“ Input”前缀。

只要每个人都遵循命名规则,您就可以全局注册所有这些组件。

例如在BaseInputs.js中

const components = require.context(path, subfolder, regexForInputComponentFileNames)

https://webpack.js.org/guides/dependency-management/#require-context

components.keys().forEach(element => {
    const componentName = element.replace(/*Everything that is not the component name like .vue*/)

    Vue.component(componentName, () => import(path + componentName)
})

然后,您只需在应用程序的开头导入“ path / to / BaseInputs”即可。

相关问题