Select a specific row in a table with single select

294 Views Asked by At

I want to implement a method that cancels moving to the next row if data has changed. My thought was to use the on-current-change event as this provides me with the oldCurrentRow. What event should I emit with what parameters to achieve staying on the last highlighted row.

You can find a fiddle here https://jsfiddle.net/arjanno/pdazb5kf/28/

Key is what happens here

    onCancel: function () {
       //Move back to oldCurrentRow
       this.$Message.info(`Clicked cancel`);
    }

As long as you don't set data dirty you should be able to click on any row. When you click Dirty it should show a modal asking you if you want to lose your changes. On cancel I want to stay on the row I was before clicking on another row.

1

There are 1 best solutions below

1
Sergio On BEST ANSWER

I don't think we can know the index of the row by the data the on-current-change callback gives us. This can/should be changed since its useful, fell free to open a issue for it.

In any case what you can do is to compare the last selected row with the current data set and use the _highlight key to tell i-table which row to highlight.

Example: https://jsfiddle.net/pdazb5kf/40/

The code would be:

function rowToString(row) {
  const data = ['name', 'age', 'address'].map(key => row[key]);
  return JSON.stringify(data);
}
export default {
  data() {
    return {
      columns3: [{
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: 'Name',
          key: 'name'
        },
        {
          title: 'Age',
          key: 'age'
        },
        {
          title: 'Address',
          key: 'address'
        }
      ],
      dirty: false,
      modal1: false,
      data1: [{
          name: 'John Brown',
          age: 18,
          address: 'New York No. 1 Lake Park',
          date: '2016-10-03'
        },
        {
          name: 'Jim Green',
          age: 24,
          address: 'London No. 1 Lake Park',
          date: '2016-10-01'
        },
        {
          name: 'Joe Black',
          age: 30,
          address: 'Sydney No. 1 Lake Park',
          date: '2016-10-02',
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        }
      ]
    }
  },
  methods: {
    onCurrentChange: function(currentRow, oldCurrentRow) {
      this.lastIndex = rowToString(oldCurrentRow);
      if (this.dirty) {
        this.modal1 = true;
      }

    },
    onCancel: function() {
      //Move back to oldCurrentRow
      this.$Message.info(`Clicked cancel`);
      this.data1 = this.data1.map((row, i) => {
        return {
          ...row,
          _highlight: rowToString(row) === this.lastIndex
        }
      });
    }
  }
}