Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how alert id of clicked element with vue js?

I am trying to understand how vue.js works. I would like to alert the id of the clicked element but when I try to do that nothing happens. I cannot see the alert.

This is my code:

<template>
    <div>
        <div class="row">
            <img src="images/retro.jpg" class="card img-fluid" id="pc_left">
            <img src="images/retro.jpg" class="card img-fluid" id="pc_center">
            <img src="images/retro.jpg" class="card img-fluid" id="pc_right">
        </div>
        <div class="row">
            <img src="images/retro.jpg" class="card img-fluid" id="player_left" rel="0">
            <img src="images/retro.jpg" class="card img-fluid" id="player_center" rel="0">
            <img @click="change(this.id)" src="images/retro.jpg" class="card img-fluid" id="player_right" rel="5">
        </div>
        {{ cards[3] || '5' }}
    </div>
</template>

<script>
export default {
    data() {
        return {
            cards: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
            '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40'],
        }
    },
    methods: {
        change(id) {
            alert(id);
        }
    }
}
</script>

<style scoped>
.card {
    border-radius: 10%;
}
</style>

I receive the following error in the developer tools:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'id' of null"

found in

---> <Card> at resources/js/components/Card.vue
       <Root>

TypeError: Cannot read property 'id' of null
    at click (app.js:37977)
    at invokeWithErrorHandling (app.js:39987)
    at HTMLImageElement.invoker (app.js:40312)
    at HTMLImageElement.original._wrapper (app.js:45671)

I suppose that the problem is the passed parameter this.id. Can someone help?

like image 663
Michele Della Mea Avatar asked Dec 18 '25 09:12

Michele Della Mea


1 Answers

Use $event to capture the event and get the id:

<img @click="change($event)" src="images/retro.jpg" class="card img-fluid" id="player_right" rel="5">

...

  methods: {
      change(event) {
          alert(event.target.id);
      }
  }
like image 141
Anurag Srivastava Avatar answered Dec 20 '25 00:12

Anurag Srivastava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!