1
votes

The idea is to use a Vue functional component as a wrapper and have some logic to decide which component to render. This pattern is illustrated in this page of the Vue docs

I want to achieve the same but lazy loading the components like this:

Vue.component('smart-list', {
  functional: true,
  props: {
    items: {
      type: Array,
      required: true
    },
    isOrdered: Boolean
  },
  render: function (createElement, context) {
    function appropriateListComponent() {
      var items = context.props.items

      if (items.length === 0) return () => import(@/components/EmptyList)
      if (typeof items[0] === 'object') return () => import(@/components/TableList)
      if (context.props.isOrdered) return () => import(@/components/OrderedList)

      return () => import(@/components/UnorderedList)
 
    }

//This creates an infinite loop to this same function
    return createElement(
      appropriateListComponent(),
      context.data,
      context.children
    )
  }
})

Notice the dynamic imports () => import(@/components/EmptyList)

The component is dynamically resolved but when passing the appropriateListComponent function to the render function and executing it produces an infinite loop

What am I missing?

1

1 Answers

0
votes

I figured it out. Creating the dynamic imports at the top of the file works as expected.

const EmptyList = () => import('@/components/EmptyList')
const TableList = () => import('@/components/TableList')
const OrderedList = () => import('@/components/OrderedList')
const UnorderedList = () => import('@/components/UnorderedList')

Vue.component('smart-list', {
  functional: true,
  props: {
    items: {
      type: Array,
      required: true
    },
    isOrdered: Boolean
  },
  render: function (createElement, context) {
    function appropriateListComponent() {
      var items = context.props.items

      if (items.length === 0) return EmptyList
      if (typeof items[0] === 'object') return TableList
      if (context.props.isOrdered) return OrderedList

      return UnorderedList

    }

//This creates an infinite loop to this same function
    return createElement(
      appropriateListComponent(),
      context.data,
      context.children
    )
  }
})