Vue.js嵌套动态组件

时间:2018-11-08 15:36:52

标签: javascript vue.js vuejs2 components nested-loops

知道我可能会有更多的孩子,是否有另一种方法可以在VueJS中嵌套组件?

我事先不知道代码中将包含哪个组件,因此我使用动态组件,但它们中始终会有多个子组件,而数量却不一定相同

这是我找到的唯一解决方案 还有另一种方法吗?

来自我的html:

<component :is="blocksElements[0].componentId">
    <component :is="blocksElements[0].child.componentId" v-if="blocksElements[0].hasChild">
        <component :is="blocksElements[0].child.child.componentId" v-if="blocksElements[0].child.hasChild" v-bind="blocksElements[0].child.child.props">
            <component :is="blocksElements[0].child.child.child.componentId" v-if="blocksElements[0].child.child.hasChild" v-bind="blocksElements[0].child.child.child.props"></component>
        </component>
    </component>
</component>

来自我的js:

blocksElements: [
    {
        componentId: 'row',
        hasChild: true,
        child: {
            componentId: 'column',
            hasChild: true,
            child: {
                componentId: 'block-image',
                hasChild: true,
                props: {
                    logo: true,
                    width: '120'
                },
                child: {
                    componentId: 'block-image',
                    hasChild: false,
                    props: {
                        logo: true,
                        width: '120'
                    }
                }
            }
        }
    }
]

2 个答案:

答案 0 :(得分:1)

您可以使用渲染功能来实现此目的:https://vuejs.org/v2/guide/render-function.html

这是一个例子(我写得很快,所以您可以进一步改进它):

<script>
import Row from './Row.vue'
import Column from './Column.vue'
import BlockImage from './BlockImage.vue'

export default {
  components: {
    Row,
    Column,
    BlockImage
  },
  data () {
    return {
      blocksElements: [
      {
        componentId: 'row',
        hasChild: true,
        child: {
          componentId: 'column',
          hasChild: true,
          child: {
            componentId: 'block-image',
            hasChild: true,
            props: {
              logo: true,
              width: '120'
            },
            child: {
              componentId: 'block-image',
              hasChild: false,
              props: {
                logo: false,
                width: '130'
              }
            }
          }
        }
      }
      ]
    }
  },

  render: function (h) {
    let els = []
    let result = null
    const buildElementBlocks = function (el) {
      els.unshift(el)
      if (el.hasChild) {
        return buildElementBlocks(el.child)
      }
      result = h(el.componentId, { props: el.props })
      els
        .splice(1)
        .forEach(element => {
          result = h(element.componentId, {
            props: element.props
          }, [result])
        })
    }
    buildElementBlocks(this.$data.blocksElements[0])
    return result
  }
}
</script>

我希望这会有所帮助!

答案 1 :(得分:0)

是的,存在,使用树菜单,vue.js有一个示例:https://br.vuejs.org/v2/examples/tree-view.html,这是递归。