vue在脚本中使用js引用元素

Vue using js in script to refer to elements

所以我在 Whosebug Convert Text to Image using javascript 中关注 post 但在 vue Js 中。我似乎无法正常工作,它向我抛出了这个错误

serve.vue?bf12:27 Uncaught TypeError: Cannot read properties of null (reading 'getContext')
    at eval (serve.vue?bf12:27:1)
    at Object../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader-v16/dist/index.js?!./dev/serve.vue?vue&type=script&lang=js (app.js:997:1)
    at __webpack_require__ (app.js:849:30)
    at fn (app.js:151:20)
    at eval (serve.vue?5c0c:1:1)
    at Module../dev/serve.vue?vue&type=script&lang=js (app.js:962:1)
    at __webpack_require__ (app.js:849:30)
    at fn (app.js:151:20)
    at eval (serve.vue?061e:1:1)

这是我的代码,很简单

<template>
  <div id="app">
    <canvas id="textCanvas" height="20" />
    <img id="image" />
    <br />
    <textarea id="text" />
  </div>
</template>

<script>
var tCtx = document.getElementById("textCanvas").getContext("2d"), //Hidden canvas
  imageElem = document.getElementById("image");

document.getElementById("text").addEventListener(
  "keyup",
  function () {
    tCtx.canvas.width = tCtx.measureText(this.value).width;
    tCtx.fillText(this.value, 0, 10);
    imageElem.src = tCtx.canvas.toDataURL();
    console.log(imageElem.src);
  },
  false
);
</script>

渲染引擎在您调用 documents.getElementById('textCanvas') 时尚未渲染 HTML。

事实上,说实话,你的代码根本不是 Vue。 Vue 有一个名为 mounted 的生命周期钩子,它在渲染引擎完成渲染组件时发生。为了使用它,您需要将上面的代码转换为实际的 Vue。

类似于此:

<template>
  <div id="app">
    <canvas ref="canvas" height="20" />
    <img id="image" />
    <br />
    <textarea @keyup="handleKeyUp" />
  </div>
</template>

<script>
export default {
  computed: {
    canvas() {
      return this.$refs.canvas;
    }; 
  },
  methods: {
    handleKeyUp() {
       // Do your thing with "this.canvas"
    }
  }
}
</script>

我真的建议你先学习 Vue 的基本概念和语法,然后再尝试这样的事情。