在vuejs应用程序中,有3个组件-- TopClicks.vue,TopImpressions.vue,TopCtr.vue。每一种方法都使用vue-好桌子 (组件本身并不重要,可以是任意的)来呈现几乎相同的表,但排序不同:
../components/TopClicked.vue (almost 200 lines)
<template>
<div class="top-clicked">
<vue-good-table
mode="remote"
@on-page-change="onPageChange"
@on-sort-change="onSortChange"
:sort-options="{
enabled: true,
initialSortBy: {field: 'clicks', type: 'desc'}
}"
...
>
<template slot="table-row" slot-scope="props">
<template v-if="props.column.field === 'keyword'">
...
</template>
<template v-else-if="props.column.field === 'clicks'">
...
</template>
<template v-else-if="props.column.field === 'impressions'">
...
</template>
...
</template>
<template slot="loadingContent">
<span class="vgt-loading__content">
...
</span>
</template>
<template slot="emptystate">
...
</template>
</vue-good-table>
</div>
</template>
<script>
import { VueGoodTable } from 'vue-good-table';
export default {
name: 'TopClicked',
components: { VueGoodTable},
data() {
return {
columns: [
{
label: this.$t('keyword'),
field: 'keyword',
},
{
label: this.$t('clicks'),
field: 'clicks',
},
... more columns
],
};
},
};
</script>另外两个组件-- TopImpressions.vue和TopCtr.vue几乎相同,但:sort-options param不同。
我的问题是:如何组织代码以避免在传递给vue-good-table**‘组件道具或插槽模板时多次进行相同的更改?组件应该是什么样的,它将默认的道具和插槽传递给另一个组件,但在需要时可以重写它们?**
如果能够创建并使用这样的子组件(带有基本优点和槽模板),而不是从上面复制200行代码,那就太好了。
<vue-good-table-child
// this should overwrite default :sort-options in vue-good-table-child
:sort-options="{
enabled: true,
initialSortBy: {field: 'impressions', type: 'desc'}
}"
>
// this should overwrite default named slot "loadingContent" in vue-good-table-child
<template slot="loadingContent">
...
</template>
</vue-good-table-child>这样,所有公共代码都将位于基本组件中,只有不同的道具(或插槽模板)应该传递给子组件。
发布于 2019-11-21 19:27:56
我尝试将3个几乎相同的组件合并到一个组件中,该组件接收它所需的自定义sortOptions作为一个prop
// This is the merged component, TopThings.vue, it replaces the instances
// of TopClicks.vue, TopImpressions.vue, and TopCtr.vue in the parent component
<template>
<div class="top-clicked">
<vue-good-table
...
:sort-options="sortOptions"
...
/>
...
</template>
<script>
...
props: {
sortOptions: {
type: Object,
required: true,
},
},
...
</script>在您的父组件中,导入TopThings组件并调用它来代替前面三个组件中的每一个,其中每个实现都传递其各自的sortOptions。
// This is the parent component where the 3 tables are implemented as
// separate instances of <TopThings />
<template>
...
<TopThings // this is the TopClicks implementation
:sort-options="sortOptions.topClicks"
/>
...
<TopThings // this is the TopImpressions implementation
:sort-options="sortOptions.topImpressions"
/>
...
<TopThings // this is the TopCTR implementation
:sort-options="sortOptions.topCTR"
/>
...
</template>
<script>
components: {
TopThings.vue,
},
data() {
return {
sortOptions: {
topClicks: {
enabled: true,
initialSortBy: {field: 'clicks', type: 'desc'}
},
topImpressions: {
...
},
topCTR: {
...
},
},
};
},https://stackoverflow.com/questions/58980616
复制相似问题