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

  • 相关阅读:
    [APIO 2009] Atm
    Codeforces518 D. Ilya and Escalator
    [POJ2096] Collecting bugs
    [ZOJ3329] One Person Game
    [LightOJ1038] Race to 1 Again
    「NOI2003」逃学的小孩
    [HAOI2006] 旅行
    ☆ [POJ2411] Mondriaan's Dream 「状压DP」
    「POJ3311」Hie with the Pie
    「乘法逆元」 学习笔记
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9901117.html
Copyright © 2011-2022 走看看