Vue 3组件'this'可能是'undefined'

mwecs4sa  于 2023-05-29  发布在  Vue.js
关注(0)|答案(1)|浏览(229)

我试图在我的组件中使用this.$refs,但无论我把它放在组件中的哪个位置,我总是得到错误,这可能是未定义的。我在方法、lambda表达式、生命周期钩子等中尝试过,但它仍然是未定义的。我是Vue的新手,我相信它很简单。有谁知道怎么解决这个问题吗?

<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>
jdgnovmf

jdgnovmf1#

Template refs在组成API上不同:

const tabtable = ref(null)

然后将其用于安装的挂钩:

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

相关问题