vue.js html元素未更新

omvjsjqw  于 2022-12-04  发布在  Vue.js
关注(0)|答案(1)|浏览(195)

这是代码,处理鼠标移动,但标签不更新鼠标位置?为什么?这是vue.js 3代码。我想更新鼠标移动位置xy数据显示在标签上。但它不工作,什么是错的?

<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>
ymdaylpp

ymdaylpp1#

引用不能用=写入必须设置引用的.value属性
所以用mouse_x.value = x代替mouse_x = 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>

相关问题