简体   繁体   中英

Use dynamic import in Vue functional component

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?

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
    )
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM