Using v-on:click
I'd like to set a variable with the id of the div in Vue.JS - how do I reference this?
<div id="foo" v-on:click="select">...</div>
<script>
new Vue({
el: '#app',
data: {
},
methods: {
select: function(){
divID = this.id // ??
alert(divID)
}
}
})
</script>
$v is an object that calls vuelidate (at the time of writing the comment, supported in version Vue.
The use of JavaScript's getElementById is not encouraged in Vue, as it creates performance issues. Vue's ref helps you “reference” DOM elements in a more efficient way.
The v-cloak directive is a Vue. js directive that will remain on the element until the associated Vue instance finishes compilation. Combined with CSS rules such as [v-cloak] { display: none }, this directive can be used to hide uncompiled mustache bindings until the Vue instance is ready.
v-on will trigger the expression or the method specified when the click event in triggered on the button element.
You can extend your event handler with the event object $event
. That should fit your needs:
<div id="foo" v-on:click="select($event)">...</div>
The event is passed on in javascript:
export default {
methods: {
select: function(event) {
targetId = event.currentTarget.id;
console.log(targetId); // returns 'foo'
}
}
}
However, nobody will stop you from writing the short notation:
<div id="foo" @click="select">...</div>
<div id="foo" @click="select(bar, $event)">...</div>
To find more options of the v-on
directive, you can look through the corresponding entry in the vue documentation:
Vue API Documentation - v-on
Inspired by @nirazul's answer, to retrieve data attributes:
HTML:
<ul>
<li
v-for="style in styles"
:key="style.id"
@click="doFilter"
data-filter-section="data_1"
:data-filter-size="style.size"
>
{{style.name}}
</li>
</ul>
JS:
export default {
methods: {
doFilter(e) {
let curTarget = e.currentTarget;
let curTargetData = curTarget.dataset;
if (curTargetData) {
console.log("Section: " + curTargetData.filterSection);
console.log("Size: " + curTargetData.filterSize);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With