[Vuejs]-How can I select element Id with a function in Vue.js?

2👍

You can pass the event to the method and then get the id from event.target.id.

https://jsfiddle.net/tr0f2jpw/

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {    
    aFunction(event){
      alert(event.target.id);
    }
 }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div
    class="col-2 column-center"              
    id="myId"              
    @mouseover="aFunction($event)"              
  >
  some stuff
  </div>
</div>

6👍

In another way, you can make your id attribute bind with the data property, like this :

<template>
  <div class="col-2 column-center" v-bind:id="id" @mouseover="aFunction(id)">
    test
  </div>
</template>

<script>
export default {
  name: 'Test',
  data() {
    return {
      id: 'myId',
    };
  },
  methods: {
    aFunction(id) {
      alert(id);
    },
  },
};
</script>

Leave a comment