Just started learning Vue yesterday and I love it. I'm trying to trigger an event when a user clicks on an anchor with a phone number:
var phoneNumbers = new Vue({
el: "a[href^='tel:']",
methods: {
onClick() { console.log('a phone number was clicked'); }
}
})
The issue is, I would like to (in this particular case), not have to add v-on:click="" to the actual element. This is because I'm dealing with a CMS where users may add links to phone numbers where they wouldn't be adding the vue attributes to the markup.
Any way of accomplishing this?
Thanks!
You have a reference to the component's root DOM element via this.$el
.
You can add a click listener in the mounted
hook (you'll also need to remove the listener in the destroyed
hook as well):
mounted() {
this.$el.addEventListener('click', this.onClick);
},
destroyed() {
this.$el.removeEventListener('click', this.onClick);
}
Here's a working example:
Vue.config.productionTip = false;
Vue.config.devtools = false;
var phoneNumbers = new Vue({
el: "a[href^='tel:']",
methods: {
onClick() {
console.log('a phone number was clicked');
}
},
mounted() {
this.$el.addEventListener('click', this.onClick);
},
destroyed() {
this.$el.removeEventListener('click', this.onClick);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<a href="tel:5555555555">555-555-5555</a>
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