Home > Blockchain >  How do I use a primary key in Bootstrap-table-vue?
How do I use a primary key in Bootstrap-table-vue?

Time:10-26

How do I use a primary key in Bootstrap-Table-Vue? But the problem is that sometimes the id fields of the data are 0. I want automatic id assignment.

My Data:

items = [{id:0,name:'Ali'},
         {id:1,name:'Veli'},
         {id:2,name:'Berkay'},
         {id:0,name:'Mehmet'},

        ]
 <b-table
        :items="filteredItems"
        :fields="filteredFields"
        primary-key="id"
        
      />

CodePudding user response:

In that case, you can iterate the items array and add primaryKey property in each object which will contain the index.

const items = [
  {id:0, name:'Ali'},
  {id:1, name:'Veli'},
  {id:2, name:'Berkay'},
  {id:0, name:'Mehmet'}
];

items.forEach((obj, index) => {
  obj['primaryKey'] = index
});

console.log(items);

Working demo with b-data-table :

new Vue({
  el: '#app',
  data: {
    items: [
      {id:0,name:'Ali'},
      {id:1,name:'Veli'},
      {id:2,name:'Berkay'},
      {id:0,name:'Mehmet'}
    ],
    fields: [
      {
        key: 'name',
        label: 'Name'
      }
    ],
  },
  mounted() {
    this.items.forEach((obj, index) => {
      obj['primaryKey'] = index
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/bootstrap-vue.common.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.css"/>
<div id="app">
    <b-table  :items="items" :fields="fields" primary-key="primaryKey"/>
</div>

  • Related