vue js如何提醒点击元素的ID?

时间:2020-04-09 19:05:09

标签: javascript html vuejs2

我试图了解vue.js的工作方式。我想提醒cl​​icked元素的ID,但是当我尝试这样做时,什么也没有发生。我看不到警报。

这是我的代码:

<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>

我在开发人员工具中收到以下错误:

[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)

我想问题是传递的参数this.id。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

使用$event捕获事件并获取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);
      }
  }