【问题标题】:Slot content of template into my inline component将模板的内容插入我的内联组件
【发布时间】:2020-09-06 00:55:04
【问题描述】:

我有这个模板:

<template>
 <my-body-component inline-component>
    <slot/>
 </my-body-component>
</template>

并且我希望 my-body-component 成为一个内联组件,其中包含插槽中的任何内容,但是当我以这种方式渲染主体时:

const my-body-component= {
  render(h) {
    return this.$slots.default;
  }
};

我似乎无法访问 this.$slots.default。 在我自己的内联组件中获取插槽内容的好方法是什么?

我还得到:“'render' 隐式具有返回类型'any',因为它没有返回类型注释,并且在其返回表达式之一中直接或间接引用。”这个错误。

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    使用Vue.extend({}) 进行类型推断。

    只要槽包含单个元素,返回 this.$slots.default 就可以了(因为 Vue 2 不能渲染多个片段)。

    const myBodyComponent = Vue.extend({
      render(h) {
        return this.$slots.default
          ? this.$slots.default.find(vnode => vnode.tag)!
          : h('span')
      }
    })
    

    如果它可能发生,则槽包含多个元素,而不是:

    return h('div', this.$slots.default)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2017-03-08
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多