Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js add event listener inside instance?

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!

like image 260
Best Dev Tutorials Avatar asked Mar 08 '19 16:03

Best Dev Tutorials


1 Answers

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>
like image 185
thanksd Avatar answered Oct 01 '22 23:10

thanksd