0

Here is the code, that handle the mose move, but label don't update the mouse position ? why ? this is vue.js 3 code. i want to update the mouse move poistion xy data display on label. but it does not work, what's wrong ?

<script setup lang="ts">
import { onMounted, ref } from 'vue';


    let mouse_x = ref(0)
    let mouse_y = ref(0)

    onMounted(()=>{
        drawline()
    })

    function drawline() {
        let canvas = document.getElementById("myCanvas");
        let ctx = canvas.getContext("2d");
        ctx.moveTo(0,0);
        ctx.lineTo(200,200);
        ctx.stroke();
    }

    function handleMouseMove(e) {
        let x = e.clientX;
        let y = e.clientY;

        mouse_x = x;
        mouse_y = y;
        console.log(x,"," ,y)
    }

    function handleMouseClick(e) {
        console.log(e)
    }

</script>


<template>
    <div>
        <canvas id="myCanvas" width="500" height="300" @mousemove="handleMouseMove" @click="handleMouseClick"> </canvas>
        <form>
            <label> {{ mouse_x }}</label>
            <label> {{ mouse_y }}</label>
        </form>
    </div>
</template>
1

1 Answer 1

1

refs can't be written with = you must set the .value property of the ref

so instead of mouse_x = x do mouse_x.value = x

<script setup>
import { ref, onMounted } from 'vue';
const mouse_x = ref(0);
const mouse_y = ref(0);

onMounted(() => {
  drawline();
});

const drawline = () => {
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  ctx.moveTo(0, 0);
  ctx.lineTo(200, 200);
  ctx.stroke();
};

const handleMouseMove = (e) => {
  const x = e.clientX;
  const y = e.clientY;

  mouse_x.value = x;
  mouse_y.value = y;
  console.log(x, ',', y);
};

const handleMouseClick = (e) => {
  console.log(e);
};
</script>

<template>
  <div>
    <canvas
      id="myCanvas"
      width="500"
      height="300"
      @mousemove="handleMouseMove"
      @click="handleMouseClick"
    >
    </canvas>
    <form>
      <label> {{ mouse_x }}</label>
      <label> {{ mouse_y }}</label>
    </form>
  </div>
</template>
Sign up to request clarification or add additional context in comments.

1 Comment

It also helps you define refs and reactive object as const instead of let as you did in this answer. This will prevent you from accidentally trying to set the value. There is usually no reason to use let inside the script setup, the only use case I have is a setTimeout that can be cancelled and retriggered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.