Search code examples
bootstrap-vue

vue - Bootstrap-vue: Select row (primary-key) based on an object with the same key values


how can I select each rows with the same values from a separate object?

<b-table
:items="CurrentObject"
:select-mode="selectMode"
ref="selectableTable"
selectable
@row-selected="onRowSelected"
primary-key="uniqueID"
>

CurrentObject:

[
{name: 'A', uniqueID: 123, text: 'lorem ipsum'},
{name: 'B', uniqueID: 456, text: 'lorem ipsum'},
{name: 'C', uniqueID: 789, text: 'lorem ipsum'},
]

Separate Object:

[
{uniqueID: 123},
{uniqueID: 456},
{uniqueID: 789},
]

Solution

  • Using JavaScript's array.findIndex() and VueBootstrap's selectRow() seem to do it.

    Template:

    <template> 
      <b-container>
        <div>
          <h1>Current Object</h1>
          <b-table
          :items="currentObject"
          :select-mode="selectMode"
          ref="selectableTable"
          selectable
          @row-selected="onRowSelected"
          primary-key="uniqueID"
          >
          </b-table>
          <h2>Separate Object</h2>
          <div v-for='object in separateObject' @click='selectMyRow(object.uniqueID);'>{{ object.uniqueID }}</div>
        </div>
      </b-container>
    </template>
    

    Script:

    <script lang="ts">
    import { Vue } from 'vue-property-decorator';
    
    export default class HelloWorld extends Vue {
    
      selectMode = 'single';
    
      currentObject = [
        {name: 'A', uniqueID: 123, text: 'lorem ipsum'},
        {name: 'B', uniqueID: 456, text: 'lorem ipsum'},
        {name: 'C', uniqueID: 789, text: 'lorem ipsum'},
      ];
    
      separateObject = [
        {uniqueID: 123},
        {uniqueID: 456},
        {uniqueID: 789},
      ];
    
      selectMyRow(uniqueID) {
        const row = this.currentObject.findIndex(x => x.uniqueID === uniqueID);
        this.$refs.selectableTable.selectRow(row);
      }
    
      onRowSelected() {
        // do something else
      }
    }
    </script>
    

    Working example: enter image description here

    If instead, you need similar functionality using select-mode multi, use the following:

    selectMode = 'multi';
    ...
    
      selectMyRow(uniqueID) {
        const row = this.currentObject.findIndex(x => x.uniqueID === uniqueID);
        const table = this.$refs.selectableTable
        if (table.isRowSelected(row)) {
          table.unselectRow(row);
        } else {
          table.selectRow(row);
        }
      }