javascriptvue.jsvuejs2

vue, emitting vs passing function as props


Let's say I have a button component that is imported in several other components. I want the child component to not be coupled to any one type of logic that happens when the button is clicked. So I want to hold that logic in the various components that leverage this button component.

I think there are at least 2 ways of going about this.

  1. Have the child emit an event to the parents, and then let the parents define the handler.

  2. Define the handlers in the parents and pass it down as props to the button component.

I'm used to doing the latter in React. Is there a best practice in vue for this situation?


Solution

  • The Vue philosophy is props down, events up. The first option follows that closer as the event itself is emitted (up) to the parent and then handled.

    Also within a Vue SFC you have the added benefit of prefixing the bound attribute with a v-on (or @) which describes its intent as an event traveling up and not a v-bind (or :) which implies it's a prop even though its really a callback to an event.