Vue包装第三方组件

有个第三方组件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插槽

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件(Component)是Vue.js最核心的功能,也是整个架构设计最精彩的地方,当然也是最难掌握的。...
    六个周阅读 5,657评论 0 32
  • 什么是组件? 组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装...
    youins阅读 9,545评论 0 13
  • 此文基于官方文档,里面部分例子有改动,加上了一些自己的理解 什么是组件? 组件(Component)是 Vue.j...
    陆志均阅读 3,871评论 5 14
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,088评论 0 29
  • 组件注册 组件名 在注册一个组件的时候,我们始终需要给它一个名字。 该组件名就是Vue.component的第一个...
    oWSQo阅读 413评论 0 1