英文:
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>
英文:
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>
答案1
得分: 2
Template refs 在组合 API 中有所不同:
const tabtable = ref(null)
然后在 mounted 钩子中使用它:
onMounted(async () => {
tabulator = new Tabulator(tabtable.value, {/* ...其余代码在此处*/});
});
英文:
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});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论