cony
cony

Reputation: 35

Nuxt3 Tanstack table how to set checkbox default value as checked?

I'm now using shadcn datatable with Tanstack table.

I have a checkbox on the first column, but I am confused about how to check all the checkboxes as default. And also have to select/deselect when clicking on the checkbox on the header, so the defaultChecked property may not work in this case.

This is my checkbox column definition:

{
        id: 'select',
        header: ({ table }) => {
            dataTable.value = table
            return h(Checkbox, {
                'checked': table.getIsAllRowsSelected() || (table.getIsSomeRowsSelected() && 'indeterminate'),
                'onUpdate:checked': (value) => {
                    table.toggleAllRowsSelected(!!value)
                },
                'ariaLabel': 'Select all',

            })
        },
        cell: ({ table, row }) => h(Checkbox, {
            'checked': row.getIsSelected(),
            'onUpdate:checked': (value) => {
                row.toggleSelected(!!value)row.original.meter)
            },
            'ariaLabel': 'Select row',
        }),
        enableSorting: false,
        enableHiding: false,
    },

Is there a hook that I can call table.toggleAllRowsSelected() to select all, or how can I make this work?

Thanks!

Upvotes: 0

Views: 89

Answers (1)

cony
cony

Reputation: 35

I'd like to share how I finally solved the problem. There might be better solutions out there.

Datatable.vue

defineExpose({
  table,
})

parentPage.vue

//template
<DataTable ref="dataTable" :columns="columns" :data="list ?? []" ></DataTable>


// script

const dataTable = ref(null) // tanstack table

watch(dataTable, () => {
    // select all when loaded
    dataTable.value?.table?.toggleAllRowsSelected(true)
})

Upvotes: 0

Related Questions