Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a column to Bootstrap Vue Table

I am using Bootstrap Vue and would like to add a column dynamically or only show the column if some condition is met in the data. I'm trying to understand scoped slots and whether this is the direction I should take with a formatter callback function. Ideally I would like to add a column "Version 2" only if it is available in the data. I'm not sure where to start.

Code

    <b-table striped responsive hover :items="episodes" :fields="fields" :filter="filter">
           <template v-slot:cell(version_1)="data">
        <a :href="`${data.value.replace(/[^a-z]-/i,'-').toLowerCase()}`">Definition</a>
      </template>

    </b-table>
</template>
<script>
data() {

    return {
      fields: [{
          key: 'category',
          sortable: true
        },
        {
          key: 'episode_name',
          sortable: true
        },
        {
          key: 'episode_acronym',
          sortable: true
        },
        {
          key: 'version_1',
          sortable: true
        }
      ],
      episodes: [],
      versions: [],
    }

  },   
mounted() {
    return Promise.all([
        // fetch the owner of the blog
        client.getEntries({
          content_type: 'entryEpisodeDefinitions',
          select: 'fields.title,fields.category,fields.slug,fields.episodeAcronym,fields.version,sys.id'
        })

      ])
        .then(response => {
        // console.info(response[0].items);
        return response[0].items
      })
      .then((response) => {

        this.episodes = response.reduce(function( result, item){
          if ( item.fields.version === 1 ) {
          return result.concat({
            category: item.fields.category,
            episode_name: item.fields.title,
            episode_acronym: item.fields.episodeAcronym,
            version_1: 'episodes/' + item.fields.slug + '/' + item.sys.id,
          })
          }
          return result
        }, [])

        this.versions = response.reduce(function( result, item){
          if ( item.fields.version === 2 ) {
          return result.concat({
            version_2: 'episodes/' + item.fields.slug + '/' + item.sys.id,
          })
          }
          return result
        }, [])

        console.info(response);
      })
      .catch(console.error)


  },
</script>
like image 214
Shawn Avatar asked Jan 15 '20 22:01

Shawn


1 Answers

I think this is something, you are looking for:

<b-table :items="items" :fields="fields">
    <template v-for="field in dynamicFields" v-slot:[`cell(${field.key})`]="{ item }">
</b-table>

in scripts:

this.dynamicFields.push({key: 'someTestKey', label: 'Dynamic Label'})
like image 77
ulou Avatar answered Sep 30 '22 07:09

ulou