Search code examples
typescriptvuejs3html5-canvasvue-composition-api

What is the best practice when typing Template Refs in Vue3 with Composition API?


I have started working on a project and decided to use Vue3 with the Composition API and Typescript. The first step in my project is to render a football field on the screen and I am doing this using the HTMLCanvasElement. In order to access its various properties in my <script> tag, I set up a template ref for it. As the Vue Docs suggest, I declared it as const canvas = ref<HTMLCanvasElement | null>(null). However, now I have a whole bunch of code that is underlined in red, since, well, it depends on the value of canvas not being null.

My question is: should I just add the ? flag everywhere the canvas is present in code, as in canvas.value?.width? Or should I just add if statements at the beginning of every method that check wheter canvas.value is null or not?

This is the TS code. The errors are on the first 3 lines of the render method

const canvas = ref<HTMLCanvasElement | null>(null);

function fitToContainer(canvas : HTMLCanvasElement){
    canvas.width  = canvas.offsetWidth;
    canvas.height  = canvas.offsetHeight;
}

function render(ctx: CanvasRenderingContext2D) {
    // Adjusting the canvas to the right dimenstions
    fitToContainer(canvas.value);
    const canvasWidth = canvas.value.width;
    const canvasHeight = canvas.value.height;

    // ---------------- FILL FIELD WITH COLOR ----------------
    ctx.fillStyle = "#3bad59";
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);

    // ---------------- DRAW LINES ----------------
}

Solution

  • The correct time to use the ref is after component mounted,so you need choose the correct time but use ? or if.

    import { onMounted } from 'vue'; 
    // ...your code 
    onMounted(()=>{ 
    render()
    })