1

I'm trying to work on a small little program as I learn Vue.js using Mouse event modifers.

The app allows the user to click a button which increments a counter within the child template by one, and then it emits the result to the parent, which increments a total variable within the parent.

In face, this example is taken straight from the Vuejs.org website.

What the example does allow for, is clicking the left or right button to increment or decrement the values. So I was trying to recreate this using the mouse event modifiers. But my code doesn't work.

To get started I just wanted to test the right button modifier to see if there was any change.

Here is the code form that:

Vue.component('button-counter', {
template: `
    <button v-on:click.right="increment">{{ counter }}</button>
`,
data: function() {
    return {
        counter: 0
    }
},
methods: {
    increment: function() {
        this.counter += 1;
        this.$emit('increment');
    }
}
})

var root = new Vue({
el: '#app',
data: {
    total: 0
},

methods: {
    incrementTotal: function() {
        this.total += 1;
    }
}
})

Here is my html code

<div id="app">
   <p>Total {{ total }}</p>
     <button-counter v-on:increment="incrementTotal"></button-counter>
     <button-counter v-on:increment="incrementTotal"></button-counter>
</div><!-- end #app -->

Of course, I'm assuming that the .right modifier has to be on the click event, because the Vuejs.org website doesn't specify which event these modifiers are for. They modifiers for the keys are a little more straight forward.

I should also note that I did try this example with the mousedown.right but it didn't work. The mousedown event works, but not when I add in the .right modifier.

But any help would be great. Thanks.

Kaley36
  • 233
  • 9
  • 19

1 Answers1

1

v-on:mousedown.right should work. Here is an example. I also added some code to prevent the context menu from displaying when the button is configured to use right clicks.

console.clear()


Vue.component('button-counter', {
  props: ["button"],
  template: `
    <button v-if="button === 'right'" 
            v-on:mousedown.right="increment" 
            v-on:contextmenu.prevent="">
      {{ counter }}
    </button>
     <button v-else 
            v-on:click="increment">
      {{ counter }}
    </button>`,
  data: function() {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function() {
      this.counter += 1;
      this.$emit('increment');
    },
  }
})

var root = new Vue({
  el: '#app',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function() {
      this.total += 1;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.js"></script>
<div id="app">
  <p>Total {{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal" button="right"></button-counter>
</div>
<!-- end #app -->
Bert
  • 80,741
  • 17
  • 199
  • 164