Vue.js鼠标事件处理程序修改器

时间:2017-07-14 13:31:44

标签: vue.js mouseevent modifier

当我使用鼠标事件修改器学习Vue.js时,我正在努力学习一个小程序。

该应用程序允许用户单击一个按钮,该按钮将子模板中的计数器递增1,然后将结果发送到父级,这将增加父级中的总变量。

从表面上看,这个例子直接来自Vuejs.org网站。

该示例允许的是单击向左或向右按​​钮来递增或递减值。所以我试图使用鼠标事件修饰符重新创建它。但我的代码不起作用。

要开始,我只想测试右键修饰符以查看是否有任何更改。

以下是代码表格:

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;
    }
}
})

这是我的HTML代码

<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 -->

当然,我假设.right修饰符必须在click事件上,因为Vuejs.org网站没有指定这些修饰符用于哪个事件。它们的键的修饰符更直接。

我还应该注意到我确实用mousedown.right尝试了这个例子,但它没有用。 mousedown事件有效,但是当我添加.right修饰符时却没有。

但任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:1)

v-on:mousedown.right应该有效。这是一个例子。我还添加了一些代码,以防止在按钮配置为使用右键单击时显示上下文菜单。

&#13;
&#13;
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;
    }
  }
})
&#13;
<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 -->
&#13;
&#13;
&#13;