vue 继承组件的slots

我想给一个组件(el-input) 添加几个prop,需要继承这个组件。

这是以前的写法:

  <el-input v-bind="$attrs" v-on="$listeners" :style="styles" :size="size"
    @input="$emit('input', $event)" :value="value" class="my-input"
  >
    <slot name="prefix" slot="prefix"></slot>
    <slot name="suffix" slot="suffix"></slot>
    <slot name="prepend" slot="prepend"></slot>
    <slot name="append" slot="append"></slot>
    <slot></slot>
  </el-input>
export default {
  computed: {
    styles() {
      const { width, minWidth, maxWidth } = this
      return { width, minWidth, maxWidth }
    }
  },
}

这种继承方式太麻烦了,需要把所有slot都列出来。

现在想改用jsx去继承:


export default {
  name: 'myInput',
  props: {
    width: { type: [String, Number] },
  },
  computed: {
    style: vm => ({
      width: vm.width,
    })
  },
  render (h) {
    return (
      <el-input { ...{ props: this.$attrs, on: this.$listeners } } class="my-input" style={ this.style } scopedSlots={ this.$scopedSlots }>
      </el-input>
    )
  }

}

其中 scopedSlots={ this.$scopedSlots }没有效果,要怎么写才能把el-input的slot都继承上呢?

阅读 9.4k
2 个回答
render (h) {
  return (
    <el-input { ...{ props: this.$attrs, on: this.$listeners } }>
      {
        Object.entries(this.$slots).map(([name, slot]) => (
          <template slot={ name }>{ slot }</template>
        ))
      }
    </el-input>
  )
}
新手上路,请多包涵

不知道这样子能不能满足你的需求

 <el-input v-bind="$attrs" v-on="$listeners" :style="styles" :size="size"
    @input="$emit('input', $event)" :value="value" class="my-input"
  >
    <slot v-for="(name) in Object.keys(this.$slots)"  :name="name" :slot="name"></slot>
  </el-input>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题