[Vuejs]-Passing a button as a table column title in Vuejs

3👍

what about doing something like this?

    <th>
      <button v-if="column.isBtn">{{column.title}}</button>
      <template v-else>{{column.title}}</template>
    </th>

now in your columns array make the last object look like this:

{
  title: "View all",
  isBtn: true
}

so what I did is only add button to the table header column and only show it when I pass isBtn with value true in the column object

Hope this code can help you.

1👍

I recommend to use scoped slots in order to customize the rendering of that cell :

Vue.component('BaseTable', {

  props: ['columns', 'data'],

  template: `<table>
<thead>
  <tr >
    <th v-for="(col,i) in columns" :key="i">
     <template  v-if="col.key && $scopedSlots[col.key]" >
        <slot :name="col.key" :column="col"></slot>
     </template>
     <template v-else>
         {{col.title}}
     </template>
    </th> 
       
  </tr>
</thead>
</table>`

})


var app = new Vue({
  el: '#app',

  data: {
    employees: [{
        "id": "1",
        "employee_name": "Tiger Nixon",
        "employee_salary": "320800",
        "employee_age": "61",
        "profile_image": ""
      },
      {
        "id": "2",
        "employee_name": "Garrett Winters",
        "employee_salary": "170750",
        "employee_age": "63",
        "profile_image": ""
      },
      {
        "id": "3",
        "employee_name": "Ashton Cox",
        "employee_salary": "86000",
        "employee_age": "66",
        "profile_image": ""
      },
      {
        "id": "4",
        "employee_name": "Cedric Kelly",
        "employee_salary": "433060",
        "employee_age": "22",
        "profile_image": ""
      },
      {
        "id": "5",
        "employee_name": "Airi Satou",
        "employee_salary": "162700",
        "employee_age": "33",
        "profile_image": ""
      },
      {
        "id": "6",
        "employee_name": "Brielle Williamson",
        "employee_salary": "372000",
        "employee_age": "61",
        "profile_image": ""
      }
    ],
    columns: [{
        title: 'ID',

      },

      {
        title: 'employee name',

      },
      {
        title: 'employee salary',

      },
      {
        title: 'employee age',

      },
      {
        title: 'View All',
        key: 'viewall'
      },
    ]
  },


})
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

<div id="app">
  <base-table :columns="columns">
    <template v-slot:viewall="{col}">
        <button class="btn btn-primary">+View All</button>
     </template>
  </base-table>
</div>

Leave a comment