在包含所有功能的较小基础组件的基础上构建更大组件的真正好方法是什么?就像 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/