提问人:David M 提问时间:5/28/2023 更新时间:5/28/2023 访问量:362
Vue 3 组件 'this' 可能是 'undefined'
Vue 3 component 'this' is possibly 'undefined'
问:
我正在尝试在我的组件中使用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>
答:
2赞
Nikola Pavicevic
5/28/2023
#1
模板引用在组合 API 中有所不同:
const tabtable = ref(null)
然后在挂载的钩子中使用它:
onMounted(async () => {
tabulator = new Tabulator(tabtable.value, {<...rest of my code here});
});
评论
0赞
David M
5/29/2023
谢谢!我在一些在线参考资料中看到了这一点,但我不知道如何正确绑定 ref(null)。
0赞
ShadowGames
7/10/2023
在应得的功劳上给人功劳!;) @DavidM
评论