If you want to do something like that you could just apply the event listener manually by adding a ref on the element you want to apply the event to, then using that to bind the event listener in the mounted hook if the condition is met:
Markup
<button ref="button">
Mouse Over Me
</button>
Vue Instance
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
}
})
Here's a JSFiddle for that: https://jsfiddle.net/0fderek6/
If you don't like that approach, you could also use a directive and place the conditional in there, you could then place that in a mixin to make it reusable:
Mixin
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 Instance
new Vue({
el: '#app',
mixins: [mouseEvents]
})
Markup
<button v-mouse-events>
Mouse Over Me
</button>
Here's the JSFiddle for that: https://jsfiddle.net/nq6x5qeq/
EDIT
If you like the directive approach, all you need to do is add an unbind hook to remove the listener, you can then have the binding arg be the event type and the binding value be the handler:
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)
}
}
});
Now all you need to do is add each listener exactly like you would with v-bind:
<div v-mouse:mouseover="mouseOverFunction"></div>
Here's the JSFiddle to show you how that works: https://jsfiddle.net/59ym6hdb/
v-if hasMouseand have one branch with the events and the other without. Probably use scoped slots to insert the common code..stop).stop.