Search code examples
javascriptvue.jsvue-tables-2

How to get a table row's index in vue-tables-2


I've inherited someone else's vue code that uses vue-tables-2. The table looks like this (very, very simplified)...

<v-client-table :data="myRows" :columns="columns" :options="options">
    <div slot="columnA" slot-scope="{row}">
        <input type="text" v-model.trim="row.someKey" class="form-control">
    </div>
    <div slot="etc"> ...

Notice how it says slot-scope="{row}", instead of slot-scope="row". As I inspect rows, I find each row looks like this...

 { row: { keyA: value, keyB: value, etc }, index: 1 },
 { row: { keyA: value, keyB: value, etc }, index: 2 }, etc

So I guess the original author "destructured" the row to avoid wasting keystrokes, as in v-model.trim="row.row.someKey".

Now I'm adding a new column which uses the row and the array index of the row data, like this...

    <div slot="columnZ" slot-scope="row">
        <p>col value is {{row.row.someOtherKey}} and index is {{row.index-1}}<p> 
    </div>

But I don't like row.row any better than the original author, and the row.index is given in counting numbers, not the zero-based array index.

I assume vue-tables-2 is the source of both of these issues. Is there a way I can use the package but just get the row data without having it wrapped in another "row", and is there a way I can get a zero-based array index per row?


Solution

  • Is there a way I can use the package but just get the row data without having it wrapped in another "row"

    Yes and no. Slot props (anything the component shares with it's slot) is always shared as a singe object. You are the one who gives the variable the name.

    So in case of slot="columnZ" slot-scope="row" (which is by the way a deprecated syntax - current syntax is v-slot:columnZ="row")

    1. You can chose any other name - instead of row it can be props or anything else
    2. what you get is whole object - { row: { keyA: value, keyB: value, etc }, index: 1 } (assuming)

    But you can destructure the object into components - v-slot:columnZ="{ row, index }"

    This is same operation as in plain JS:

    const obj = { row: { keyA: 1, keyB: "asdasd", }, index: 1 }
    // here the names `row` and `index` are given by the names of 1st level properties
    const { row, index } = obj
    
    console.log(row)
    console.log(index)
    
    // it is possible to "rename" te variable
    const { row: user } = obj
    console.log(user)

    As for the missing zero-based index - if this is what the component shares with the slot, there is very little you can do about it. The component is in control. If you really need it, just add one more key into every row containing zero-based index