Vue包装第三方组件

2019-04-15  本文已影响0人  seaasun

有个第三方组件Third-Component, 你想包装再利用,可以如下写:

<Third-Component v-bind="$attrs" v-on="$listeners">
    <template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope">
      <slot :name="slot" v-bind="scope"/>
    </template>
    <slot/>
</Third-Component>

例子

比如你常用UI组件库中的弹框组件Modal,每次调用时需将其width设为1000:

<Modal width="1000">
 // ...
</Modal

你不想每次调用都写width="1000" ,因为可能以后需改为width=800,你希望width="1000" 只出现一次。
你可以创建一个新组件my-modal,组件内容如下:

<template>
  <Modal 
         v-bind="$attrs"  
         v-on="$listeners"
         :width="1000">
    <template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope">
      <slot :name="slot" v-bind="scope"/>
    </template>
    <slot/>
  </Modal>
</template>

<script>
  export default {
    name: "myModal",
  }
</script>

以后你只需调用<my-modal>即可。在My-Modal中可以用Modal的全部props,事件监听和slot。

分析

v-bind="$attrs" 

传递所有的prop

v-on="$listeners"

传递所有的监听

<template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope">
      <slot :name="slot" v-bind="scope"/>
</template>

遍历并写入所有的slot插槽

上一篇 下一篇

猜你喜欢

热点阅读