0
0
Vueframework~5 mins

Mouse button modifiers in Vue

Choose your learning style9 modes available
Introduction

Mouse button modifiers help you run code only when a specific mouse button is clicked. This makes your app respond exactly how you want.

You want to do something only when the right mouse button is clicked, like showing a custom menu.
You want to ignore clicks from the middle mouse button to avoid unwanted actions.
You want to handle left clicks differently from right clicks on a button.
You want to prevent default browser actions on certain mouse clicks.
You want to add special effects only when a specific mouse button is pressed.
Syntax
Vue
<element @click.left="handler">...</element>
<element @click.right="handler">...</element>
<element @click.middle="handler">...</element>

Use .left, .right, or .middle after the event name to specify the mouse button.

This works with mouse events like click, mousedown, and mouseup.

Examples
This button runs sayLeft only when the left mouse button is clicked.
Vue
<button @click.left="sayLeft">Left Click</button>
This div triggers showMenu only on right mouse button down.
Vue
<div @mousedown.right="showMenu">Right Click Here</div>
This span runs middleAction only when the middle mouse button is released.
Vue
<span @mouseup.middle="middleAction">Middle Click</span>
Sample Program

This Vue component has three buttons. Each button listens for clicks from a specific mouse button using modifiers. The message below changes depending on which button is clicked. The right click also uses .prevent to stop the browser's context menu.

Vue
<template>
  <div>
    <button @click.left="handleLeftClick">Left Click Me</button>
    <button @click.right.prevent="handleRightClick">Right Click Me</button>
    <button @click.middle="handleMiddleClick">Middle Click Me</button>
    <p>{{ message }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('Click a button')

function handleLeftClick() {
  message.value = 'Left button clicked!'
}

function handleRightClick() {
  message.value = 'Right button clicked!'
}

function handleMiddleClick() {
  message.value = 'Middle button clicked!'
}
</script>
OutputSuccess
Important Notes

The .right modifier often needs .prevent to stop the browser's context menu from showing.

Mouse button modifiers only work with mouse events, not keyboard events.

Test your app on different devices because some mice or touchpads may behave differently.

Summary

Mouse button modifiers let you run code only for left, right, or middle mouse clicks.

Use .left, .right, or .middle after event names like @click.

They help make your app respond exactly to the mouse button the user presses.