Binding parent function in component slot...?

I am currently looking at a pull request with some strange looking code in it. Problem is, I don’t know if it is technically incorrect?

I would love to hear your thoughts on the matter, and if you would like to propose alternatives that would be great too.

The problem is that the dev is binding a parent function in the component slot, here is the code:

Parent Component:

import DropDown from '.../_dropDown.js';

Vue.component('Parent' {
    props: {
        // ...some props
    },
    components: {
        DropDown
    },
    methods: {
        someLogic() {
            // ...perform some logic
        }
    },
    template: `
        <div>
            <!-- some other html and such -->
            <drop-down>
                <select @change="someLogic">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select >
            </drop-down>
        </div>
    `
});

The child-component:

Vue.component('DropDown' {
    template: `
        <div class="consistent-styles">
            <slot></slot>
        </div>
    `
});

The purpose of the component was to create drop down lists with a consistent look and feel across the site. This was achieved by styling via a class in the component.

In my opinion the custom component should accept a list of options as a prop and emit an event whenever a new one is selected. The parent can then listen for the event and fire “someLogic” function whenever it is emitted, rather than binding the function on the slot template.

I don’t know if his approach is technically incorrect though, and would love to hear what you think!

Technically there is nothing wrong with what he has done.
Would I do it though? No not really.
A component to me (drop-down) handles everything within in, within its own file so I don’t bloat the parent file with code for a child component. If the function is needed in the parent component then I would do as you said and pass down props and emit events - this is recommended and common practice.

In your current set up you will need to pass down your slot content every time you have a drop down child component which is obvious anti DRY. If the slot content was within the child component then you just need to import and use the child component, bobs your uncle!

Hope that helps

From the docs

,

1 Like

Agreed with this. If you did want to provide a way to change the slot template you could use scoped slots.

1 Like