zoukankan      html  css  js  c++  java
  • 使用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语法可能不太一样

    来源:https://segmentfault.com/a/1190000016747615

  • 相关阅读:
    详细分析Orchard的Content、Drivers, Shapes and Placement 类型
    什么是现代的应用程序?
    MySQL锁详解!(转载)
    EF DataFirst修改数据类型
    EF+LINQ事物处理
    .net防止SQL注入的一种方式
    .net解决Xss攻击
    IDEA创建Struts2报错——web.xml
    WebServer搭建过程
    设计模式——观察者模式
  • 原文地址:https://www.cnblogs.com/datiangou/p/10130577.html
Copyright © 2011-2022 走看看