首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用槽扩展Vue组件

如何用槽扩展Vue组件
EN

Stack Overflow用户
提问于 2020-11-24 22:33:55
回答 1查看 2K关注 0票数 1

我想要一个第三方库组件,多添加一个元素,并以与往常一样的方式使用这个第三方。

示例:

代码语言:javascript
复制
<third-party foo="bar" john="doe" propsFromOriginalLibrary="prop">
  <template v-slot:top=v-slot:top={ props: test }>
    Some text on third-party component slot
  </template>
</third-party>

希望将代码编码为:

代码语言:javascript
复制
<my-custom-component propsFromOriginalLibrary="prop">
  <template v-slot:top={ props: test }>
    Some text on third-party component slot
  </template>
</my-custom-component>

这两个例子都是一样的。我可以通过以下方式获得所有的道具:

代码语言:javascript
复制
<third-party v-bind="$attrs">

但不确定如何处理插槽

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-25 02:49:21

以下是您可以这样做的方法:

my-custom-component 模板:

代码语言:javascript
复制
<template>
  <third-party v-bind="$attrs">
    <template v-slot:top="slotProps">
      <slot name="top" v-bind="slotProps"></slot>
    </template>
  </third-party>
</template>

发生了什么:

插入第三方组件和$attrs

  • Referencing parent

  • Custom的top时隙

  • 自定义组件有一个插槽,该插槽被传递到第三方的时隙

  • 自定义插槽中具有相同的名称,因此从插槽v-bind的所有第三方slotProps传递给父H 222G 223的方式与v-slot相同。

您可以使用v-for来避免对每个插槽的内部模板进行硬编码。例如,如果您想公开两个插槽,topbottom

代码语言:javascript
复制
<template>
  <third-party v-bind="$attrs">
    <template v-for="slot in ['top','bottom']" v-slot:[slot]="slotProps">
      <slot :name="slot" v-bind="slotProps"></slot>
    </template>
  </third-party>
</template>

演示:

代码语言:javascript
复制
Vue.component('third-party', {
  props: ['background'],
  template: `
  <div class="third" :style="{ background }">
    3rd party slot:
    <div class="third-slot">
      <slot name="top" :props="props"></slot>
    </div>
  </div>
  `,
  data() {
    return {
      props: 'Third party Prop'
    }
  },
})

Vue.component('my-custom-component', {
  template: `
  <div>
    <component is="third-party" v-bind="$attrs">
      <template v-for="slot in ['top']" v-slot:[slot]="slotProps">
        <slot :name="slot" v-bind="slotProps"></slot>
      </template>
    </component>
  </div>
  `
})

/***** APP *****/
new Vue({
  el: "#app"
});
代码语言:javascript
复制
.third,.third-slot {
  padding: 10px;
}
.third-slot {
  background: #cccccc;
  border: 1px solid #999999;
  font-weight: bold;
}
代码语言:javascript
复制
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
<div id="app">
  <third-party background="#eeeeff">
    <template v-slot:top="{ props: test }">
      Some text on third-party component slot
      <div>{{ test }}</div>
    </template>
    
  </third-party>

  <my-custom-component background="red">
    <template v-slot:top="{ props: test }">
      Some text on third-party component slot
      <div>{{ test }}</div>
    </template>
  </my-custom-component>
</div>

乐趣:,您甚至可以使包装好的组件动态化,比如<component :is="thirdpartyName">和插槽名数组;甚至可以从外部传递这些信息,作为一个完全通用的包装器。但这里没有必要

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64995842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档