Vue3 TypeError:模板 ref.value 为 null

wit*_*ein 18 templates canvas refs vuejs3 vue-composition-api

如何清除控制台中的以下错误:

在此输入图像描述

TypeError: ref.value is null

该错误仅在调整大小事件时出现。每次调整窗口大小时,都会渲染图表。于是错误信息一次又一次的出现。文档显示模板引用也用空值初始化(Source)进行初始化。所以初始化后我必须做一些事情,对吗?

这是我的代码:

<template>
  <canvas
    ref="chartRef"
  />
</template>
Run Code Online (Sandbox Code Playgroud)
<script setup>
// ...
// on resize
export const chartRef = ref(null)
export function createChart () {
  const ctx = chartRef.value.getContext('2d')
  if (ctx !== null) { // fix me
    getDimensions()
    drawChart(ctx)
  }
}
// ...
</script>

Run Code Online (Sandbox Code Playgroud)

如何清理我的控制台以便不再出现错误消息?谢谢。

Don*_*ony 32

我有点太晚了,但我在 Vue 3 中遇到了同样的问题。我通过返回引用解决了 juste :

<template>
  <input ref="myinput">
</template>


<script>
import { onMounted, ref } from 'vue'

export default {
  setup() {

    const myinput = ref(null) // Assign dom object reference to "myinput" variable

    onMounted(() => {
      console.log(myinput.value) // Log a DOM object in console
    })

    return { myinput } // WILL NOT WORK WITHOUT THIS
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)


ube*_*kel 16

如果您看到yourRef.valueas ,null那么您尝试获取 to 的元素可能ref位于 false 内v-ifref在实际需要该元素之前,Vue 不会实例化。


Dan*_*iel 7

选项A

将它包裹在一个try...catch

选项2

用一个watch


我发现最好的方法是使用watch

下面是一个可以在多个组件之间重用的函数的示例。我们可以定义一个函数来生成画布引用,然后将其传递给组件 - canvasRef

const withCanvasRef = () => {
  let onMountCallback = null;
  const onMount = callback => {
    onMountCallback = callback;
  };
  const canvasRef = ref(null);

  watch(canvasRef, (element, prevElement) => {
    if (element instanceof HTMLCanvasElement) {
      canvasRef.value = element;
      if (onMountCallback && prevElement === null) onMountCallback(canvasRef);
    } else {
      ctxRef.value = null;
    }
  });
  return {
    canvasRef,
    onMount
  };
};
Run Code Online (Sandbox Code Playgroud)

然后我们可以获取canvasRef组件中的 并将其传递给<canvas>元素。我们还可以使用onMounted函数返回的钩子来处理初始渲染。

app.component("my-line-chart", {
  setup: props => {
    const { canvasRef, onMount } = withCanvasRef();

    const draw = () => {
      // stuff here,
      // use a check for canvasRef.value if you have conditional rendering
    };

    // on resize
    window.addEventListener("resize", () => draw());

    // on canvas mount
    onMount(() => draw());

    return { canvasRef };
  },
  template: `<div><canvas ref="canvasRef"/></div>`
});
Run Code Online (Sandbox Code Playgroud)

请参阅示例以了解实际情况。希望您能够看到使用 Composition API 作为更好的代码重用和组织解决方案的好处。(尽管它的某些方面看起来有点费力,比如必须手动定义道具的手表)

const app = Vue.createApp({
  setup() {
    const someData = Vue.ref(null);
    let t = null;

    const numPts = 20;
    const generateData = () => {
      const d = [];
      for (let i = 0; i < numPts; i++) {
        d.push(Math.random());
      }

      if (someData.value == null) {
        someData.value = [...d];
      } else {
        const ref = [...someData.value];
        let nMax = 80;
        let n = nMax;
        t !== null && clearInterval(t);

        t = setInterval(() => {
          n = n -= 1;
          n <= 0 && clearInterval(t);
          const d2 = [];
          for (let i = 0; i < numPts; i++) {
            //d2.push(lerp(d[i],ref[i], n/nMax))
            d2.push(ease(d[i], ref[i], n / nMax));
          }
          someData.value = [...d2];
        }, 5);
      }
    };
    generateData();
    return { someData, generateData };
  }
});

const withCanvasRef = () => {
  let onMountCallback = null;
  const onMount = callback => {
    onMountCallback = callback;
  };
  const canvasRef = Vue.ref(null);

  Vue.watch(canvasRef, (element, prevElement) => {
    if (element instanceof HTMLCanvasElement) {
      canvasRef.value = element;
      if (onMountCallback && prevElement === null) onMountCallback(canvasRef);
    } else {
      ctxRef.value = null;
    }
  });
  return {
    canvasRef,
    onMount
  };
};

const drawBarGraph = (canvas, data) => {
  const width = canvas.width;
  const height = Math.min(window.innerHeight, 200);
  const ctx = canvas.getContext("2d");

  const col1 = [229, 176, 84];
  const col2 = [202, 78, 106];

  const len = data.length;
  const mx = 10;
  const my = 10;
  const p = 4;
  const bw = (width - mx * 2) / len;

  const x = i => bw * i + p / 2 + mx;
  const w = () => bw - p;
  const h = num => (height - my * 2) * num;
  const y = num => (height - my * 2) * (1 - num) + my;
  const col = i => {
    const r = lerp(col1[0], col2[0], i / len);
    const g = lerp(col1[1], col2[1], i / len);
    const b = lerp(col1[2], col2[2], i / len);
    return `rgb(${[r, g, b]})`;
  };

  data.forEach((num, i) => {
    ctx.fillStyle = col(i);
    ctx.fillRect(x(i), y(num), w(), h(num));
  });
};

const drawLineGraph = (canvas, data) => {
  const width = canvas.width;
  const height = Math.min(window.innerHeight, 200);
  const ctx = canvas.getContext("2d");

  const col1 = [229, 176, 84];
  const col2 = [202, 78, 106];

  const len = data.length;
  const mx = 10;
  const my = 10;
  const p = 4;
  const bw = (width - mx * 2) / len;

  const x = i => bw * i + p / 2 + mx + bw / 2;
  const y = num => (height - my * 2) * (1 - num) + my;
  const r = 2;

  const col = i => {
    const r = lerp(col1[0], col2[0], i / len);
    const g = lerp(col1[1], col2[1], i / len);
    const b = lerp(col1[2], col2[2], i / len);
    return `rgb(${[r, g, b]})`;
  };

  ctx.lineWidth = 0.2;
  ctx.strokeStyle = "black";
  ctx.beginPath();
  data.forEach((num, i) => {
    i == 0 && ctx.moveTo(x(i), y(num));
    i > 0 && ctx.lineTo(x(i), y(num));
  });
  ctx.stroke();
  ctx.closePath();

  data.forEach((num, i) => {
    ctx.beginPath();
    ctx.fillStyle = col(i);
    ctx.arc(x(i), y(num), r, 0, 2 * Math.PI);
    ctx.fill();
  });
};

const drawSomething = canvas => {
  canvas.width = window.innerWidth / 2 - 5;
  canvas.height = Math.min(window.innerHeight, 200);
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgb(255 241 236)";
  ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
};

app.component("my-bar-chart", {
  props: ["data"],
  setup: props => {
    const { canvasRef, onMount } = withCanvasRef();

    const draw = () => {
      if (canvasRef.value) {
        drawSomething(canvasRef.value);
        drawBarGraph(canvasRef.value, props.data);
      }
    };

    // on resize
    window.addEventListener("resize", () => draw());

    // on data change
    Vue.watch(
      () => props.data,
      () => draw()
    );

    // on canvas mount
    onMount(() => draw());

    return { canvasRef };
  },
  template: `<div><canvas ref="canvasRef"/></div>`
});

app.component("my-line-chart", {
  props: ["data"],
  setup: props => {
    const { canvasRef, onMount } = withCanvasRef();

    const draw = () => {
      if (canvasRef.value) {
        drawSomething(canvasRef.value);
        drawLineGraph(canvasRef.value, props.data);
      }
    };

    // on resize
    window.addEventListener("resize", () => draw());

    // on data change
    Vue.watch(
      () => props.data,
      () => draw()
    );

    // on canvas mount
    onMount(() => draw());

    return { canvasRef };
  },
  template: `<div><canvas ref="canvasRef"/></div>`
});

app.mount("#app");

const lerp = (start, end, amt) => (1 - amt) * start + amt * end;
const ease = (start, end, amt) => {
  return lerp(start, end, Math.sin(amt * Math.PI * 0.5));
};
Run Code Online (Sandbox Code Playgroud)
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
.chart {
  display: inline-block;
  margin-right: 4px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>

<div id="app">
  <button @click="generateData">Scramble</button>
  <div>
    <my-bar-chart class="chart" :data="someData"></my-bar-chart>
    <my-line-chart class="chart" :data="someData"></my-line-chart>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)