简体   繁体   English

在 Vue 功能组件中使用动态导入

[英]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.这个想法是使用 Vue 功能组件作为包装器,并有一些逻辑来决定要渲染哪个组件。 This pattern is illustrated in this page of the Vue docs此模式在 Vue 文档的此页面中进行了说明

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)注意动态导入() => 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该组件是动态解析的,但是当将适当的ListComponent 函数传递给渲染函数并执行它时会产生无限循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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