Answer the question
In order to leave comments, you need to log in
How to make a circle that follows the cursor in vue,js?
Why doesn't it work?
<body>
<div class="app">
<div class="circle"></div>
</div>
<script>
new Vue({
el: `.app`,
data: {
circle: document.querySelector(`.circle`)
},
methods: {
move(e) {
this.circle.style.left = e.pageX + `px`;
this.circle.style.top = e.pageY + `px`;
}
},
created() {
document.addEventListener(`mousemove`, this.move);
}
});
</script>
</body>
Answer the question
In order to leave comments, you need to log in
data: {
circle: document.querySelector(`.circle`)
},
.app
with elements that it will create itself. If you want to have access to them, there is a special mechanism for this . That is, add the ref attribute to the element .circle
:
In the move method, replace with :<div class="circle" ref="circle"></div>
this.$refs.circle.style.left = `${e.pageX}px`;
this.$refs.circle.style.top = `${e.pageY}px`;
The way you're trying to solve a problem is more like jQuery than vue.
Here's how to get the cursor position: https://codepen.io/martinandersen3d/pen/eeKZGb
Next, you can create a computed property that returns an object with a style that will set the position of the object you need. Well, accordingly, bind this object to your div (:style="objectWithPosition"). I think with css everything will be clear.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question