Search code examples
javascriptvue.jsvuejs2bootstrap-vue

sort table based on index with b-buttons (up and down)


I'm working with BootstrapVue.

I have a table where I can input rows with my b-button. After inserting different rows I want to have a - I will name it sort function.

So I want to be able to change the order with two buttons (here: Up and Down) based on their index. So the index should always be the same but the ID should switch.

Also I have - if my index is equal to zero - disabled the button because I could not be able to go "higher". This I also want on the last element..

Thanks for helping me out!

This is how it looks for better understanding:

enter image description here

INFO You should be able to copy paste the code and it should work.

Code of template

<template>
  <div>
    <b-button @click="addNewItem()">Add Input</b-button>

    <h3 class="mt-5 ml-3 mb-2"><strong>Created Table</strong></h3>
        <table class="table table-striped col-md-12 mt-4">
          <tr>
            <div class="row mt-2 mb-2">
              <th class="col-md-1 ml-4">INDEX</th>
              <th class="col-md-1">ID</th>
              <th class="col-md-1">CHANGE #</th>
            </div>
          </tr>
          <tr v-for="(item, index) in inputs" :key="item.id">
            <div class="row mt-2 mb-2">
              <td class="col-md-1 ml-4">#{{ index + 1 }}</td>
              <td class="col-md-1 mr-1">{{item.id}}</td>
              <td class="col-md-3">
                <b-button :disabled="index == 0" size="sm mr-1">Up</b-button>
                <b-button size="sm">Down</b-button>
              </td>
            </div>
          </tr>
        </table>

  </div>
</template>

Code of script

<script>
  export default {
    data() {
      return {
        inputs: [{
          id: 1
        }],
        id: 1,
      }
    },

    methods: {
      addNewItem() {
        this.inputs.push({
          id: this.id += 1
        })
      }
    }
  }
</script>

Solution

  • I think the answer is self-explanatory ..

    TEMPLATE

    <b-button :disabled="index == 0" @click="sortUp(index)"><b-icon icon="arrow-up"></b-icon></b-button>
    <b-button :disabled="index == (inputs.length - 1)" size="sm"><b-icon icon="arrow-down" @click="sortDown(index)"></b-icon></b-button>
    

    SCRIPT

    sortUp(index) {
      var element = this.inputs[index];
      this.inputs.splice(index, 1);
      this.inputs.splice(index-1, 0, element);
    },
    
    sortDown(index) {
      var element = this.inputs[index];
      this.inputs.splice(index, 1);
      this.inputs.splice(index+1, 0, element);
    },