2017-07-14 85 views
1

我正在尝试使用鼠标事件修饰符学习Vue.js,因此我正在尝试使用一个小程序。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修改必须是在点击事件,因为Vuejs.org网站并未指定这些修饰符适用于哪个事件。它们的键修饰符更简单一点。

我也应该注意到,我确实尝试了这个例子与mousedown.right,但它没有奏效。 mousedown事件起作用,但当我添加.right修饰符时不起作用。

但任何帮助将是伟大的。谢谢。

+0

您使用Vue的哪个版本? – aprouja1

+0

我在使用2.4的cdn – Kaley36

回答

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