Categories
Vue Answers

How to Listen for Right Clicks with Vue.js?

Spread the love

Sometimes, we want to listen for right clicks and do something when the user right-clicks on an element with Vue.js.

In this article, we’ll look at how to listen for right clicks and do something when the user right-clicks on an element with Vue.js.

Listen for Right Clicks with Vue.js

To listen for right clicks and do something when the user right-clicks on an element with Vue.js, we can use the @contextmenu directive to listen for contextmenu events, which are emitted on right-click.

For instance, we can write:

<template>  
  <div id="app">  
    <button @contextmenu.prevent="onRightClick">right click me</button>  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  methods: {  
    onRightClick() {  
      console.log("right clicked");  
    },  
  },  
};  
</script>

We add the prevent modifier to prevent the default right-click menu from showing, and instead the onRightClick method will be run when we right click on the button.

Now when we right-click on the button, we see 'right clicked' logged.

Conclusion

To listen for right clicks and do something when the user right-clicks on an element with Vue.js, we can use the @contextmenu directive to listen for contextmenu events, which are emitted on right-click.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *