【问题标题】:使用单文件组件语法将属性绑定到 $slot
【发布时间】: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>

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    我能够通过纯粹在模板中使用$slots 破解自己的方式。

    这是一个 hack,因为这个实现总是假设 slot 只会是一层深。

    如果其他人知道更好的方法,请发布答案,因为我是 Vue 新手。谢谢!

    <template>
      <p-button
        class="p-button-rounded"
        :icon="icon"
        :label="
          $slots.default &&
          $slots.default
            .map((node) => node.text)
            .join('')
            .trim(' ')
        "
        iconPos="right"
        v-on="$listeners"
      />
    </template>
    
    <script>
    import Button from "primevue/button";
    import VueTypes from "vue-types";
    
    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]),
      },
    };
    </script>
    

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 1970-01-01
      • 2016-12-10
      • 2014-04-23
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多