一个文件内写多个vue组件

使用render函数

<template>
    <LabelRender :label-arr="labelArr">
      <template #test>
        <div>
          123
        </div>
      </template>
    </LabelRender>
</template>
<script>
// inline component
const LabelRender = {
  props: {
    labelArr: {
      type: Object,
      default: () => []
    }
  },
  render(h) {
    return h('el-descriptions', { attrs: { column: 2, border: true }}, // attrs 添加html属性
      this.labelArr.map(item => h('el-descriptions-item', { attrs: { label: item.label }},
        item.slot && this.$scopedSlots[item.prop] // this.$scopedSlots 获取组件插槽
          ? this.$scopedSlots[item.prop]() //  ()内可传递参数 使用#test=""接收
          : [h('span', { class: item.class }, item.label)]
      ))
    )
  }
}
export default {
  name: 'app',
  components: {
    LabelRender
  }
}
</script>

使用JSX

  1. 实际上会编译为渲染函数
  2. v-bind v-for 等vue专有方法不能使用
  3. vue中仍使用class而不是className
<template>
    <LabelRender :label-arr="labelArr">
      <template #test="{ }">
        <div>
          123
        </div>
      </template>
    </LabelRender>
</template>
<script>
// inline component with JSX
const LabelRender = {
  props: {
    labelArr: {
      type: Object,
      default: () => []
    }
  },
  render() {
    return (
      <el-descriptions column={2} border>
        {this.labelArr.map(item => {
          return (
            <el-descriptions-item label={item.label}>
              { item.slot && this.$scopedSlots[item.prop]
                ? this.$scopedSlots[item.prop]() 
                : <span class={item.class}>{item.prop}</span> }
            </el-descriptions-item>
          )
        })}
      </el-descriptions>
    );
  } 
};

export default {
  name: 'app',
  components: {
    LabelRender
  }
}
</script>

参考地址

  1. 如何在一个文件中写多个Vue组件(译-有删改)open in new window
  2. 渲染函数 & JSXopen in new window
  3. 学Vue,就要学会vue JSXopen in new window
  4. Vue2 + JSX使用总结open in new window
  5. vue中render函数使用attrs绑定id、class、style、事件open in new window
Last Updated:
Contributors: haizhiguang