Kagashino的Vue.js提高班

【Vue.js】使用HoC渲染动态组件列表

2019-11-05  本文已影响0人  Kagashino

编写动态组件列表时,一般会使用如下方式

<component :is="comp.name" v-for="comp in list"></component>
{
  compontents: {
    foo,
    bar,
    baz
  },
  data: {
    list: [{name: 'foo'}, {name: 'bar'}, {name:'baz'}]
  }
}

这样处理会有一个问题,如果需要渲染多个foo组件(或者其他重复的组件),同一组件之间的数据会被缓存对一个组件绑定数据更改会触发其他同名组件数据的更改,但是如果使用<keep-alive>缓存组件状态,则友会导致组件不能重复渲染。

原因

<component />的设计目的,是为了应对像tab标签页类似的场景,这些场景对页面唯一性要求比较高,所以同名的component,数据会缓存

解决方法

使用HoC的思想,建立一个组件容器,利用render创建动态的组件列表:

const components = {
  foo, bar, baz
}

export const ComponentPod {
  functional: true, // 无状态容器
  render(createElement, context) {
    const { data } = context;
    const { name } = data.attrs;
    return createElement(
      'div', 
      null, 
      createElement(components[name], data)
    );
  },
}
<component-pod name="item" v-for="item in list" />
上一篇 下一篇

猜你喜欢

热点阅读