2017-07-14 45 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 -->