基于其他较小的基础组件构建组件的最佳方法是什么?

What’s the best way to build components based on other, smaller base components?

在包含所有功能的较小基础组件的基础上构建更大组件的真正好方法是什么?就像 OOP 世界中的接口。

我正在尝试这样的事情,但感觉很糟糕。

ReportItem.vue - 基础组件

<template>
  <div class="report-item">
    <div class="report-item__actions">
      <button @click="onEdit" type="button">Edit</button>
      <button @click="onDelete" type="button">Delete</button>
    </div>
    <div class="report-item__content">
      <slot></slot>
    </div>
  </div>
</template>
<script>
import '../styles/_report-item.css';
export default {
  name: 'report-item',
  props: {
    data: Object,
    type: String,
  },
  methods: {
    onEdit() {
      console.log("Editing...")
    },
    onDelete() {
      console.log("Deleted");
    }
  }
}
</script>

ReportItemText - 具有相同编辑和删除功能但内容更多的更大组件。

<template>
  <report-item class="report-item--title">
    <h4>{{title}}</h4>
  </report-item>
</template>
<script>
import ReportItem from './ReportItem';
export default {
  name: 'report-item-title',
  components: {ReportItem},
  data() {
    return {
      title: 'Report Title'
    }
  }
}
</script>

有没有更好的方法使用 mixins 甚至 .extend 来做到这一点,但允许自定义模板? 这是一个 codesandbox link 到现在使用这种方法的代码 - https://codesandbox.io/s/4jmw1l7xow

它是所有内容的混合体,但与 mixins 一起,您应该使用 slots - 特别是命名和范围。

使用范围插槽,您可以在范围范围内访问 children 的属性,并根据您的要求修改渲染。这与命名插槽一起,为您提供了完全灵活的渲染内容。一个简单的例子是:

// child-component
<div>
  <slot :childInternalProperty="objectInData">
    {{ childInternalProperty.name }}
  </slot>
</div>

// main
<child-component> <!-- will render the name -->
</child-component>

<child-component> <!-- will render "Hello!" -->
  Hello!
</child-component>

<child-component> <!-- will render "Hello {the name} !" -->
  <template slot-scope="slotProps"> <!-- template goes into child-component's slot -->
    Hello {{ slotProps.childInternalProperty.name }}!
  </template>
</child-component>

您基本上要做的是使用 child 的数据从外部自定义 child 的模板。

希望对您有所帮助。祝你好运!