Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue click event on multiple td elements exception on first and last

I want to use a click event in my table to go to the detailpage of the clicked row with the exception on the first and last td element.

Example:

<tr v-for="(row, key) in $rows" :key="row.id">
  <td>*Input checkbox*</td>
  <td>{{ row.user.type }}</td>
  <td>{{ date | moment('MMMM') }}</td>
  <td>{{ row.customer.name }}</td>
  <td>{{ row.user.name }}</td>
  <td>{{ row.total }}</td>
  <td>*Icon to archive*</td>
</tr>

What I can't use because of exception on first and last element:

<tr @click="detailPage(row.user.id)" v-for="(row, key) in $rows" :key="row.id">

What I don't want to use because of repeating code:

<tr v-for="(row, key) in $rows" :key="row.id">
  <td>*Input checkbox*</td>
  <td @click="detailPage(row.user.id)">{{ row.user.type }}</td>
  <td @click="detailPage(row.user.id)">{{ date | moment('MMMM') }}</td>
  <td @click="detailPage(row.user.id)">{{ row.customer.name }}</td>
  <td @click="detailPage(row.user.id)">{{ row.user.name }}</td>
  <td @click="detailPage(row.user.id)">{{ row.total }}</td>
  <td>*Icon to archive*</td>
</tr>

What I tried but didn't trigger the click event:

<tr v-for="(row, key) in $rows" :key="row.id">
  <td>*Input checkbox*</td>
  <template @click="detailPage(row.user.id)">
    <td>{{ row.user.type }}</td>
    <td>{{ date | moment('MMMM') }}</td>
    <td>{{ row.customer.name }}</td>
    <td>{{ row.user.name }}</td>
    <td>{{ row.total }}</td>
    <td>*Icon to archive*</td>
  </template>
</tr>

How I could solve with JQuery:

$('table#tbl > tbody > tr > td').not(':first').not(':last').click(function() {
  // detailpage
})

Method from click event

methods: {
  detailPage (id) {
    this.$router.push({path: `/timesheets/view/${id}`})
  },

Is there a right way in Vue without repeating code?

like image 564
EnzoTrompeneers Avatar asked Feb 04 '19 08:02

EnzoTrompeneers


1 Answers

You can add this event modifier on the td element you don't want to trigger with the click :

v-on:click.stop=""

or just :

@click.stop

and leave the @click on the tr element.

You can check the documentation for more informations : https://v2.vuejs.org/v2/guide/events.html

new Vue({
  el: '#app',
  data: {
    message: 1
  },
  methods:{
  add(){
  this.message++;
  }
  }
})
td {
  border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <tr @click="add()">
      <td>Hello</td>
      <td v-on:click.stop="">Visitor n° {{message}}</td>
    </tr>
  </table>
</div>
like image 187
F_Mekk Avatar answered Nov 02 '22 20:11

F_Mekk