Vue3 - 如何在子组件中使用在父组件的 onMounted 挂钩中启动的实例

Vue3 - How to use instance initiated in parent component's onMounted hook, in the child component

我在 onMounted() 生命周期挂钩中启动变量(制表符)时遇到问题,因此当我将制表符实例作为 prop 传递给子组件时,它始终为空,因为我想启动发生在子组件创建之后。

简单的说:我想在子组件中使用在父组件中声明和启动的实例。

Tabulator 要求我在 onMounted() 挂钩中启动它,所以我无法摆脱它。

父组件

<template>
    <div>
        <AddRowButton :tabulator="tabulator" />
        <div ref="table"></div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { TabulatorFull as Tabulator } from 'tabulator-tables'
import AddRowButton from '@/components/buttons/AddRowButton.vue'

interface Props {
    data: Array
}

const props = withDefaults(defineProps<Props>(), {
    data: Array
})

let tabulator = null
const table = ref(null)

onMounted(() => {
    tabulator = new Tabulator(table.value, {
        data: props.data,
        columns: [
            { title: 'Id', field: 'id', sorter: 'number' },
            { title: 'Name', field: 'name', sorter: 'string' },
            { title: 'Email', field: 'email', sorter: 'string' },
            { title: 'Date', field: 'date', sorter: 'date' }
        ]
    })
})

子组件

<template>
    <button @click="addNewRow">Add row</button>
</template>

<script setup lang="ts">
import { TabulatorFull as Tabulator } from 'tabulator-tables'

defineProps({
    tabulator: Tabulator
})

function addNewRow(): void {
    try {
        tabulator.addData({}, true) // Tabulator always null
    } catch (error) {
        console.log(error.message)
    }
}

</script>

谢谢!

您将制表符属性定义为 null 类型

defineProps({
  tabulator: null
})