I'm new to vue.js and trying to build a component which triggers a popup which will follow the mouse position when hovering over an element. The problem is that the mouse position is only logged when entering/leaving the element instead of everytime the mouse is moved within the element. How would I get this to work correctly?
<template>
<div>
<div class="hover" @mouseenter="mouseEnter" @mouseleave="mouseLeave"></div>
<div class="popup" v-if="popup">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
popup: false
}
},
methods: {
mouseEnter() {
console.log('mouseneter');
this.popup = true;
this.$el.addEventListener('mousemove', this.mouseMove());
},
mouseLeave() {
console.log('mouseleave');
this.popup = false;
this.$el.removeEventListener('mousemove', this.mouseMove());
},
mouseMove() {
console.log(event.clientX, event.clientY);
}
}
}
</script>
<style lang="scss" scoped>
.hover {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
}
.popup {
position: absolute;
top: 0;
left: 100%;
}
</style>
Emitting Events with setup() $emit() to send our event. Instead, we can access our emit method by using the second argument of our setup function – context . context has access to your components slots, attributes, and most importantly for us, its emit method. We can call context.
Events mouseenter and mouseleave Events mouseenter/mouseleave are like mouseover/mouseout . They trigger when the mouse pointer enters/leaves the element.
The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.
<template>
<div>
<div class="hover" @mouseenter="mouseEnter" @mousemove="mousemove" @mouseleave="mouseLeave"></div>
<div class="popup" v-if="popup">
<slot></slot>
</div>
</div>
<script>
export default {
data() {
return {
popup: false
}
},
methods: {
mouseEnter(event) {
console.log('mouseneter');
this.popup = true;
this.$el.addEventListener('mousemove', this.mouseMove, false);
},
mouseLeave(event) {
this.popup = false;
// this.$el.removeEventListener('mousemove', this.mouseMove());
},
mouseMove(event) {
console.log(event.clientX, event.clientY);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With