我想要一个第三方库组件,多添加一个元素,并以与往常一样的方式使用这个第三方。
示例:
<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>希望将代码编码为:
<my-custom-component propsFromOriginalLibrary="prop">
<template v-slot:top={ props: test }>
Some text on third-party component slot
</template>
</my-custom-component>这两个例子都是一样的。我可以通过以下方式获得所有的道具:
<third-party v-bind="$attrs">但不确定如何处理插槽
发布于 2020-11-25 02:49:21
以下是您可以这样做的方法:
my-custom-component 模板:
<template>
<third-party v-bind="$attrs">
<template v-slot:top="slotProps">
<slot name="top" v-bind="slotProps"></slot>
</template>
</third-party>
</template>发生了什么:
插入第三方组件和$attrs
top时隙
v-bind的所有第三方slotProps传递给父H 222G 223的方式与v-slot相同。您可以使用v-for来避免对每个插槽的内部模板进行硬编码。例如,如果您想公开两个插槽,top和bottom
<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>演示:
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"
});.third,.third-slot {
padding: 10px;
}
.third-slot {
background: #cccccc;
border: 1px solid #999999;
font-weight: bold;
}<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">和插槽名数组;甚至可以从外部传递这些信息,作为一个完全通用的包装器。但这里没有必要
https://stackoverflow.com/questions/64995842
复制相似问题