P
P
pavuuuk2019-09-24 21:16:32
Vue.js
pavuuuk, 2019-09-24 21:16:32

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>

I just started learning vue today and haven't fully read the documentation yet. But it seems to me that it should work, or am I wrong somewhere?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-09-24
@pavuuuk

data: {
    circle: document.querySelector(`.circle`)
},

It makes no sense to keep references to template elements. After the Vue instance is initialized, this element will no longer be part of the page - Vue will replace the original content .appwith 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`;

https://jsfiddle.net/4esvu230/

A
Artem Lukyanov, 2019-09-25
@ArtyomPLAY

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 question

Ask a Question

731 491 924 answers to any question