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

标签 javascript vue.js components vue-component

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

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

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 链接,指向现在使用这种方法的代码 - https://codesandbox.io/s/4jmw1l7xow

最佳答案

它是一切的混合体,但与 mixins 一起你应该使用 slots - 特别命名和范围。

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

// 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 的模板。

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

关于javascript - 基于其他较小的基础组件构建组件的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52659502/

相关文章:

javascript - 排列Javascript

javascript - 当 body 背景图像完成加载时显示警报

javascript - vuejs/vuex 中 Props 的顺序、计算和创建

javascript - Vuejs 和 Vuex 不呈现更新的数组

javascript - 尝试在 reactjs 中呈现时出现 webpack 问题

delphi - 需要德尔福群发邮件程序的建议

javascript - 使用 Javascript 复制到剪贴板

javascript - 简单的 jQuery Animate 示例 - 从一个 div 滚动到另一个 div

json - Vue 使用 v-model 更改 key 本身

java - 使用 javaFX 对齐文本时遇到问题