dynamically add column to datatables-vue3 table?
dynamically add column to datatables-vue3 table?
Test case:
https://jsfiddle.net/frumpty/guh4j8v3/32/
It seems not possible to add a column to a datatables-vue3 table by updating the 'columns' property the same way you can add rows by updating the 'data' property.
I am wondering if perhaps I need to re-initialize the datatable in such a situation, but I can't find an example of how to do a re-initialization with the vue3 component -- note that I did see some comments about reinitialization on the blog (https://datatables.net/blog/2022-06-22-vue), however, it glosses over what needs to happen to prepare the contexts, and I unfortunately do not have sufficient background knowledge to fill in the blanks.
Appreciate if anyone can give me some pointers.
This question has an accepted answers - jump to answer
Answers
Doesn't look like datatables supports adding columns after creation. Will need to find a way to have all the data prepared before the component is initialized.
You are correct - there is no way to dynamically add columns after initialisation. You need to know the number of columns at initialisation time.
Allan
thank you @allan .
Just to point out, Datatables issues a warning when populating from DATA that is missing some cells... (https://datatables.net/manual/tech-notes/4 )
It is better that it silently replace "missing cells" with an empty string than to throw the javascript alert(). Alternatively, using
console.log()
would be a better option perhaps?This is relatively straightforward to workaround by having an extra loop that processes the inbound data and replaces missing cells with a blank string, but I wonder if you're open to perhaps an issue being opened to "improve" (IMHO) the default behaviour?
PS.
In case you're curious about what inspired this:
I encountered this in the context of rendering a list of things with a variable number of attributes. Some things have N attributes, and others have N+1 etc. I wanted the table to have COUNT(possible attributes) columns, and to simply have empty cells for the rows corresponding to an object that didn't have a specific attribute.
An API yielding the data responds with an object such as this
{
'attributes' : [{name: x, value: y}, {name: a, value: b}...],
'data': [{...}, {...} ..]
}
that contains the entire catalogue of attributes, and then each row in the reponse can contain any number of tags from that catalogue.
I ultimately solved this by having an api call to get the data, prepare my data (including filling in blank strings for missing cells) and columns for datatables, and only then, call vue.mount()
If you have missing cells then use
columns.defaultContent
to define the empty string or whatever you want to display. This should eliminate theRequested unknown parameter
alert.Kevin
Thankyou @kthorngren I was not aware of that. I'll look into that.