あなたはそのような何かをしたい場合
マークアップ
を:あなただけの条件が満たされた場合
mounted
フックでイベントリスナーをバインドすることを利用して、その後、
element
あなたがイベントを適用する上で
ref
を追加することによって、手動でイベントリスナーを適用することができ
<button ref="button">
Mouse Over Me
</button>
Vueのインスタンス
new Vue({
el: '#app',
mounted() {
let hasMouse = true;
// If the user has a mouse, add the event listeners
if (hasMouse) {
let button = this.$refs.button
button.addEventListener('mouseover', e => {
this.mouseover = true
})
button.addEventListener('mouseout', e => {
this.mouseover = false
})
}
},
data: {
mouseover: false
}
})
ここでは、そのためにJSFiddleです:https://jsfiddle.net/0fderek6/
あなたはそのアプローチが気に入らない場合、あなたはまたdirective
を使用して、そこに条件を置くことができ、あなたは可能性がありそれをmixin
に入れて再利用できるようにします。
ミックスイン
<button v-mouse-events>
Mouse Over Me
</button>
const mouseEvents = {
directives: {
mouseEvents: {
bind(el, binding, vnode) {
let hasMouse = true;
if (hasMouse) {
el.addEventListener('mouseover', e => {
vnode.context.mouseover = true
})
el.addEventListener('mouseout', e => {
vnode.context.mouseover = false
})
}
}
}
},
data: {
mouseover: false
}
}
Vueのインスタンス
new Vue({
el: '#app',
mixins: [mouseEvents]
})
マークアップは、ここではそのためJSFiddleです:https://jsfiddle.net/nq6x5qeq/
EDIT
あなたがdirective
アプローチが好きなら、あなたがする必要があるすべてのリスナーを削除するunbind
フックを追加している、あなたはその後、binding arg
は、イベント型で持つことができるとbinding value
ハンドラなる:
Vue.directive('mouse', {
bind(el, binding) {
if (hasMouse) {
console.log(binding.arg + ' added')
// bind the event listener to the element
el.addEventListener(binding.arg, binding.value)
}
},
unbind(el, binding) {
if (hasMouse) {
console.log(binding.arg + ' removed')
el.removeEventListener(binding.arg, binding.value)
}
}
});
は、今あなたがする必要があるすべてはv-bind
と正確にご希望の各リスナーを追加している:ここではそれがどのように動作するかをお見せするためにJSFiddleだ
<div v-mouse:mouseover="mouseOverFunction"></div>
:https://jsfiddle.net/59ym6hdb/
あなたは 'V-IF hasMouse'を使用して、イベントやなしに他との一方の枝を持っている可能性が...あなたの ユースケースごとに評価します。おそらく[scoped slots](https://vuejs.org/v2/guide/components.html#Scoped-Slots)を使用して共通コードを挿入します。 –
非常に単純なコンポーネントであれば問題ありませんが、テンプレートが充実している場合(私はこの場合複雑なSVGで作業しています)、痛みになります – asi
計算されたプロパティはすばらしい答えに見えます。あなたがそれを打ち込み、受け入れられた答えとしてマークしたくない理由はありますか? –