Vue.js 鼠标事件处理程序修饰符
Posted
技术标签:
【中文标题】Vue.js 鼠标事件处理程序修饰符【英文标题】:Vue.js Mouse Event Handler Modifers 【发布时间】:2017-07-14 13:31:43 【问题描述】:当我使用鼠标事件修饰符学习 Vue.js 时,我正在尝试开发一个小程序。
该应用允许用户单击一个按钮,该按钮将子模板中的计数器加一,然后将结果发送给父模板,父模板中的总变量递增。
这个例子直接取自 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 修饰符必须在点击事件上,因为 Vuejs.org 网站没有指定这些修饰符用于哪个事件。它们的键修饰符更直接一些。
我还应该注意,我确实使用 mousedown.right 尝试了这个示例,但它不起作用。 mousedown 事件有效,但当我添加 .right 修饰符时无效。
但是任何帮助都会很棒。谢谢。
【问题讨论】:
你使用的是哪个版本的 Vue? 我正在使用 CDN 到 2.4 【参考方案1】:v-on:mousedown.right
应该可以工作。这是一个例子。我还添加了一些代码,以防止在将按钮配置为使用右键单击时显示上下文菜单。
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 -->
【讨论】:
以上是关于Vue.js 鼠标事件处理程序修饰符的主要内容,如果未能解决你的问题,请参考以下文章