Home > Blockchain >  Vue 3 convert ref to other Type with instanceof with Typescript
Vue 3 convert ref to other Type with instanceof with Typescript

Time:12-27

So in Vue with the Options API I have the following Code:

<script lang="ts">
import * as THREE from 'three';

export default {
    mounted() {
        console.assert(this.$refs.container instanceof HTMLCanvasElement, this.$refs.container);
        const renderer = new THREE.WebGLRenderer({
            canvas: this.$refs.container as HTMLCanvasElement,
            antialias: true,
            alpha: true
        });
        
    }
};
</script>

<template>
    <canvas ref="container" id="earthCanvas"></canvas>
</template>

Now if I want to port that to the Composition API, the call to "this" does not work anymore, because it is "possibly undefined" (why, btw?). So I want to use 'ref' and 'container.value' instead:

<script lang="ts">
import * as THREE from 'three';
import { onMounted, ref } from 'vue';

let container = ref(null)
onMounted(() => {
    console.assert(container.value instanceof HTMLCanvasElement, container.value);
    const renderer = new THREE.WebGLRenderer({
        canvas: container.value as HTMLCanvasElement,
        antialias: true,
        alpha: true
    });

});
</script>

<template>
    <canvas ref="container" id="earthCanvas"></canvas>
</template>

However, Vue is not happy with what I made: When I call 'container.value', it says: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter".

Now how do I convert a ref to the element? I'm just a beginner so sorry for posting such a simple question...

chatGPT can not show me what I'm doing wrong, If I'm using it's code I get other Errors...

CodePudding user response:

Your container value has this type: Ref<null>. So it's a reference to the null value, and Typescript infer this to be always the type null.

To specify which type your ref should be, you have to use the generic parameter:

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

When properly typed, your instanceof will work.

CodePudding user response:

Instead of assert, you might just want to do a branch check to see if ref is null:

let container = ref<HTMLCanvasElement | null>(null)
onMounted(() => {
  if (container.value) {
    const renderer = new THREE.WebGLRenderer({
        canvas: container.value,
        antialias: true,
        alpha: true
    });
  }
});
  • Related