skip to Main Content

I’d like to bind 2 mouse click events to a div field. One of them is a shift+click, the other is a regular click, eg.

<div @click.shift="aaa()" @click="bbb()">...</div>

The problem is when I shift+click on the div not only aaa() is executed, but bbb(), too.
I tried to use some modifiers, eg. @click.shift.stop or similar, but bbb() has been executed all the time I clicked on the div. How can I solve this without separating the 2 kind of click events in a single function, eg. ccc() that calls either aaa() or bbb()?

3

Answers


  1. new Vue({
      el: '#app',
      methods: {
        aaa() {
          console.log('aaa() executed!');
        },
        bbb(event) {
          if (!event.shiftKey) {
            console.log('bbb() executed!');
          }
        }
      }
    })
          div {
    
            background-color: green;
            padding: 20px;
    
          }
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
        <div id="app">
          <div @click.shift="aaa()" @click="bbb($event)">Click me!</div>
        </div>

    hope this helps!

    Login or Signup to reply.
  2. I’d do it like so, add a single click handler which will dispatch the event accordingly.

    new Vue({
      el: '#app',
      methods: {
        aaa() {
          console.log('aaa() executed!');
        },
        bbb(event) {
          if (!event.shiftKey) {
            console.log('bbb() executed!');
          }
        }
        ccc(event){
          if (event.shiftKey) {
            this.aaa(event);
          }else{
            this.bbb(event);
          }
        }
      }
    })
          div {
    
            background-color: green;
            padding: 20px;
    
          }
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
        <div id="app">
          <div @click="ccc($event)">Click me!</div>
        </div>
    Login or Signup to reply.
  3. What you are looking for is the "exact" modifier.

    <div @click.shift="aaa()" @click.exact="bbb()">...</div>
    

    https://vuejs.org/guide/essentials/event-handling.html#exact-modifier

    The .exact modifier allows control of the exact combination of system modifiers needed to trigger an event.

    So this click event will trigger only if NO modifier were used, excluding it from executing when the @click.shift is triggered. Do note that this will also prevent alt+click, ctrl+click etc.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search