使用slot-scope复制vue中slot内容

发布时间:2019-05-26 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用slot-scope复制vue中slot内容脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

有时候我们的vue组件需要复制使用者传递的内容。

比如我们工程里面的轮播组件需要使用复制的slot来达到循环滚动的效果

使用者关注轮播内容的静态效果,组件负责让其滚动起来

组件:
<div class="horse-lamp">
    <div class="lamp">
      <slot name="lamps"></slot>
    </div>
    <div class="lamp">
      <slot name="lamps"></slot>
    </div>
</div>

使用者:
<CarouselWidget>
    <div slot="lamps">123</div>
</CarouselWidget>

这种实现方式对于初始化的数据是没问题的,但是不支持slot内容的动态绑定,这是因为

  • vnode在vue中是唯一的
  • 一个vnode只会和一个dom节点绑定

因此当组件使用者在声明节点时,因为只声明了一个div,后台只生成了1个vnode,最终虽然产生了2个div,但是vnode只和后面1个dom绑定了,当vnode修改时也只会修改1个dom

解法:slot-scope
使用slot-scope数据产生的每个slot都会产生一个新的vnode

组件:
<div class="horse-lamp">
    <div class="lamp">
      <slot name="lamps" :arr="arr"></slot>
    </div>
    <div class="lamp">
      <slot name="lamps" :arr="arr"></slot>
    </div>
</div>

使用者:
<CarouselWidget :arr="info.column">
  <template scope="slotProps" slot="lamps">
      <component  v-for="(item, index) in slotProps.arr"
        :key="info.id"
        :is="templates[item.type]"
        :item="item"
      ></component>
  </template>
</CarouselWidget>

这种情况下component内容有改动,那么组件内容2个slot都会同步更新

项目使用的vue版本是2.4.2,更高级的vue的slot-scope语法可能不太一样

脚本宝典总结

以上是脚本宝典为你收集整理的使用slot-scope复制vue中slot内容全部内容,希望文章能够帮你解决使用slot-scope复制vue中slot内容所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue