[Vuejs]-How to DRY use a Vue.js component with multiple props and slots

0👍

I’d try merging the 3 nearly identical components into 1 component that receives the custom sortOptions it needs as a 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>

In your parent component, import the TopThings component and call it in place of each of your 3 previous components, where each implementation is passed its respective 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: {
                ...
            },
        },
    };
},

Leave a comment