【发布时间】:2022-01-23 02:22:17
【问题描述】:
我想做一些与this post 非常相似的事情,我想要一个属性绑定到默认插槽。但是,我想使用 单文件组件语法 而不是 Vue.component()。
换句话说,我该如何做相当于访问this.$slots?
<template>
<p-button
class="p-button-rounded"
:icon="icon"
v-on="$listeners"
/>
</template>
<script>
import Button from 'primevue/button';
import VueTypes from 'vue-types';
const getChildrenTextContent = (children) => children
?.map((node) => (node.children ? getChildrenTextContent(node.children) : node.text))
.join('')
.trim(' ');
export default {
name: 'Button',
components: { 'p-button': Button },
// inheritAttrs: false, // TODO: figure out what value this should be
props: {
type: VueTypes.oneOf(['primary', 'secondary', 'tertiary', 'ghost']).def(
'primary',
),
icon: VueTypes.oneOfType([String, null]),
},
// inspired by https://stackoverflow.com/a/42956086/858275
created() {
const text = getChildrenTextContent(this.$slots.default); // (Obviously) doesn't work because `this` refers to the current object
this.$attrs.label = text;
console.log(text);
},
};
</script>
【问题讨论】: