Search code examples
vue.jsvuejs2bootstrap-vue

How to show an empty row in BootstrapVue's b-table


I am using a b-table from BootstrapVue. However, when the array of objects for my table is empty, i want to show the table headers + 1 empty row, without any text in the cells of the table.

On BoostrapVue's b-table page, there is some explanation about showing something for an empty table, but i'm not following the explanation. There is also no visual of the outcome. When using show-empty, it gives a simple text 'no records ...', but i don't want the text. Or maybe i want a custom text (depending on the language when using i18n).

So the html is currently:

<b-table bordered :head-variant="'light'" hover :items="dogs" :fields="dogHeaders" >
</b-table>

And in the vue data i have:

dogs: [], //because i want to mimic an empty table
dogHeaders: ['name','color','age'],

Can someone show me an example how to do this?

edit: i currently see only a workaround with populating my dogs array with an empty dog like so:

dogs: [{name:'',color:'',age:''}],

But i guess there should be a better way (+ this workaround gives a row that has less height than an actual filled row)


Solution

  • Since you want to render actual cells, you can use the top-row slot instead of the standard empty slot.

    You can then conditionally render the slot using a v-if, based on whether the dogs array is empty or not. Then render empty cells (<td>) inside the slot for each element in your dogHeaders array.

    new Vue({
      el: '#app',
      data() { 
        return {
          dogs: [],
          dogHeaders: ['name', 'color', 'age']
        }
      },
      methods: {
        addRow() {
          this.dogs.push({
            name: 'Pence',
            color: 'Black',
            age: 53
          })
        }
      }
    })
    <link href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
    
    <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.js"></script>
    
    <div id="app" class="p-3">
      <b-btn @click="dogs = []">Reset Table</b-btn>
      <b-btn @click="addRow">Add row</b-btn>
      <hr />
      <b-table bordered head-variant="light" hover :items="dogs" :fields="dogHeaders">
        <template #top-row v-if="dogs.length === 0">
          <!-- Adding &nbsp; to the cell so that it maintains the standard cell height -->
          <td v-for="i in dogHeaders.length">&nbsp;</td>
        </template>
      </b-table>
    </div>