[Vuejs]-How to create Vue components with custom templates but same functionality without repeating yourself?

0๐Ÿ‘

1. Create component

./src/components/dataTableComponent.vue

<template>
    <datatable>

        <div v-if="!withTitles">
            <div v-for="(row, index) in rows" :key="index" class="header" @click="sortBy(row.field)">row.title</div>
            <div v-for="(row, index) in rows" :key="index">row.value</div>
        </div>

        <div v-id="withTitles">
            <h1>
                <span v-for="(row, index) in rows" :key="index" @click="sortBy(row.field)">row.title</span>
            </h1>
            <h3 v-for="(row, index) in rows" :key="index">row.value</h3>
        </div>

    </datatable>
</template>
<script>
export default {
    name: 'dataTableComponent',
    props: ['rows', 'withTitles'],
    data () {
        return {

        }
    },
    methods: {
        sortBy(field){
            //Code to ordre this.rows
        }
    }
}
</script>

2. Use component

<template>
    <div>

        <h2>No titles</h2>
        <dataTableComponent :rows="rows" :withTitles="ture">
        
        <h2>With Titles</h2>
        <dataTableComponent :rows="rows">

    </div>
</template>
<script>
import dataTableComponent from 'src/components/dataTableComponent.vue';

export default {
    components: {dataTableComponent},
    data () {
        return {
            rows: ['AAA', 'BBB', 'CCC']
        }
    }
}
</script>

Check Vue documentation for more options

0๐Ÿ‘

you can use vue slot : https://v2.vuejs.org/v2/guide/components-slots.html

datatable.vue

<template>
  <div>
    <slot name="table-slot"></slot>
  </div>
</template>

<script>
  export default {
    name: 'datatable'
  }
</script>

sampleComp1.vue

<template>
  <div>
    <datatable>
        <div slot="table-slot">
            // add your template data
        </div>
    </datatable>
  </div>
 </template>

 <script>
   import datatable from './datatable.vue';

   export default {
     name: 'sampleComp1',
     data() {
        rows: [] // put your values in this array
     },
     components: {
        datatable
     },
     methods: {
        sortBy(field) {
            // do something
        }
        
     }
   }
</script>

sampleComp2.vue

<template>
  <div>
    <datatable>
        <div slot="table-slot">
            // add your template data
        </div>
    </datatable>
  </div>
 </template>

<script>
  import datatable from './datatable.vue';

  export default {
    name: 'sampleComp2',
    data() {
        rows: [] // put your values in this array
    },
    components: {
        datatable
    },
    methods: {
        sortBy(field) {
            // do something
        }
    }
  }
 </script>

Leave a comment