Home > Software design >  Vue3 - How to use instance initiated in parent component's onMounted hook, in the child compone
Vue3 - How to use instance initiated in parent component's onMounted hook, in the child compone

Time:03-04

I am having an issue where I initiate a variable (tabulator) in the onMounted() life cycle hook, so when I pass the tabulator instance as prop to the child component, it will always be null because I suppose the initiated happens after the child component is created.

Simply put: I want to use an instance that is declared and initiated in the parent component, in the child component.

Tabulator requires me to initiate it in the onMounted() hook, so I can't get away from that.

Parent component

<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' }
        ]
    })
})

Child component

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

Thanks!

CodePudding user response:

You're defining the tabulator prop as type null

defineProps({
  tabulator: null
})
  • Related