简体   繁体   中英

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!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM