Adding custom controls to top bar layout using Vue

Adding custom controls to top bar layout using Vue

Quelluomo00!Quelluomo00! Posts: 2Questions: 1Answers: 0

I'm using the DataTables Vue component in a simple app. I'd like to add some buttons to the top bar, as described in https://datatables.net/examples/layout/custom-nodes.html. I'd like to add the full Vue functionality to the buttons (e.g. binding @click events and so on), but the example in the docs only works with simple HTML.
I tried adding the buttons elsewhere in my app and referencing them using ref() but it doesn't seem to be working.
I was not able to find any answer from the docs. Is there a way to achieve this?

Answers

  • Quelluomo00!Quelluomo00! Posts: 2Questions: 1Answers: 0

    I was able to solve it, here's the solution I came up with.

    I added a custom node just like in the docs:

    let toolbar = document.createElement('div');
    toolbar.id = "tableToolbar"
    
    const dataTableOptions = {
        layout: {
            topStart: toolbar
        },
        // other options
    });
    

    Then I added the button on top of my component HTML, wrapped in a Teleport tag:

    <Teleport to='#tableToolbar' v-if="mounted">
        <a class="btn btn-primary" href="#" @click="btnClick">My Button</a>
    </Teleport>
    

    Normally, the Teleport target should already exist before the component is mounted, otherwise Vue will throw a warning and the teleport will fail.
    To circumvent this, I use conditional rendering to activate the teleport only after the component is mounted. The mounted variable is set in the onMounted hook:

    let mounted = false;
    onMounted(() => {
        mounted = true;
    });
    

    This ensures that the target element exists when the teleport tries to find it.

    Hope this helps someone! Feel free to comment if you know there's a better (or official) solution, right now I'm fine with using the Teleport tag.

  • allanallan Posts: 63,441Questions: 1Answers: 10,459 Site admin

    That's cool - nice one! I wasn't actually aware of the Teleport tag, so that's really useful to know about.

    The other option is to create vnodes and render them, then return that from a function in the layout option. I know from experience that while it is perfectly possible, it isn't massively easy though!

    I'll have a bit more of a think about how Vue components could be used in layout - to be honest it never occurred to me before!

    Allan

Sign In or Register to comment.