Search code examples
typescriptvue.jsvue-componentthistabulator

Vue 3 component 'this' is possibly 'undefined'


I am trying to use this.$refs in my component but no matter where I put it in the component, I keep getting errors that this may be undefined. I've tried it in methods, lambdas, in lifecycle hooks etc, but it's still undefined. I'm new to Vue and I'm sure it's something simple. Does anyone know how to fix this?

<template>
    <div ref="tabtable"></div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref } from 'vue';
import { InventoryDataService } from '@/services/InventoryDataService';
import type { IInventoryItem } from '@/assets/interfaces/iinventoryitem';
import type { IVendor } from '@/assets/interfaces/ivendor';
import { TabulatorFull as Tabulator } from 'tabulator-tables';
// TODO: Remove this!
import { TestVendor } from "@/assets/testdata/fakevendor";

let inventory = ref<IInventoryItem[]>();
let tabulator: Tabulator;
const dataService = new InventoryDataService();
const getInventory = async (vendor: IVendor): Promise<IInventoryItem[]> => {
    return await dataService.getInventory(vendor)
};

// 'this' reference below is undefined
onMounted(async () => {
    tabulator = new Tabulator(this.$refs.tabtable, {<...rest of my code here});
});

onBeforeMount(async () => {
    inventory.value = await getInventory(TestVendor);
});
</script>

Solution

  • Template refs are different in composition api:

    const tabtable = ref(null)
    

    then use it in mounted hook:

    onMounted(async () => {
      tabulator = new Tabulator(tabtable.value, {<...rest of my code here});
    });