Search code examples
javascriptvue.jsvuejs2vue-tables-2

Linking a row in a table to a url


I am working on a vue component that implements vue-tables-2. I have a working example here. What I am trying to do is link the edit href url to the entire row as opposed to only the edit cell. Using vanilla javascript, I tried using the mounted hook (this.$el) to access the virtual dom and wrap the row in an href and hide the edit column although, it feels like a bit of a hack. Any suggestions on how to accomplish this?

  <template>
    <div class="col-md-8 col-md-offset-2">
        <div id="people">
            <v-client-table :data="tableData" :columns="columns">
                <template slot="edit" slot-scope="props">
                   <div>
                        <a class="fa fa-edit" :href="edit(props.row.id)">thing</a>
                    </div>
                </template>
            </v-client-table>
        </div>
    </div>
</template>

<script>
    import {ServerTable, ClientTable, Event} from 'vue-tables-2';
    import Vue from 'vue';
    import axios from 'axios';

    export default {
        methods: {
          edit: function(id){
                        return "edit/hello-" + id
          }
        },
        data() {
            return {
                columns: ['edit', 'id','name','age'],
                tableData: [
                    {id:1, name:"John",age:"20"},
                    {id:2, name:"Jane",age:"24"},
                    {id:3, name:"Susan",age:"16"},
                    {id:4, name:"Chris",age:"55"},
                    {id:5, name:"Dan",age:"40"}
                ]
            };
        }
    }
</script>

Solution

  • The table component emits a row-click event that you can listen to. It gives you the row that was clicked. I suggest, instead of trying to use a link, you listen for the event and navigate where you want.

    Here is the updated template.

    <v-client-table :data="tableData" :columns="columns" @row-click="onRowClick">
    

    And in the method:

    onRowClick(event){
      window.location.href = `/edit/hello-${event.row.id}`
    }
    

    Example.