【问题标题】:Use dynamic import in Vue functional component在 Vue 功能组件中使用动态导入
【发布时间】:2020-01-01 19:32:28
【问题描述】:

这个想法是使用 Vue 功能组件作为包装器,并有一些逻辑来决定要渲染哪个组件。 这种模式在this page of the Vue docs中进行了说明

我想像这样实现相同但延迟加载组件:

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

注意动态导入 () => import(@/components/EmptyList)

组件是动态解析的,但是当将适当的ListComponent 函数传递给渲染函数并执行它时会产生一个无限循环

我错过了什么?

【问题讨论】:

    标签: javascript vue.js webpack import functional-programming


    【解决方案1】:

    我想通了。在文件顶部创建动态导入按预期工作。

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

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2020-11-24
      • 2020-06-18
      • 2019-02-03
      • 2020-01-24
      • 2021-03-30
      • 2020-02-25
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多