The difference between the callback function of the vue parent and child component props and the child component emit

1. The parent component returns the callback function to the child component, passing the data as parameters in the child component to call
and
2. The emit data of the child component is given to the parent component. What"s the difference in using
in the parent component

?

I feel that all of them can be used in the first way. Why do we need emit as a sub-component?

at present, the only way I can think of is the first way. The child component can modify the method passed by the parent component, which doesn"t feel good

PS: finds another problem when the child component tries to modify the props, such as
this.props.callback = function () {alert ("overridden parent component method")} , it is possible to overwrite
but if

var a = this.props.callback
a = function(){alert("")}

this can"t be changed. It"s strange. Why?

these two questions are very confusing. I am a novice at vue, and I am grateful for the advice of the Great God.

Jun.25,2021

I feel that all of them can be used in the first way. Why do we need emit as a sub-component?

because there are sibling components in addition to parent-child components, and the event approach only applies to parent-child components.

this can't be changed. It's strange. Why?

at this point, only a points to this.props.callback , it has nothing to do with vue , and the re-assignment just points a to something else.


is very simple. Most of the time, our subcomponents only need to give the value to the upper level, and there is no need to do anything else. Of course you can send the callback in. However, in order to decouple the parent and child components, you still need to emit out when doing this child component.
because many times the entire parent component is made up of countless small child components. The unified processing logic of the parent component is much more reasonable than that of the child component alone.
components try to do their own things, not other components. In this way, maintenance is also very convenient.


1. Emit cannot communicate with sibling components. (the way of event/ event bus is completely different)

2. The difference between emit and props is that emit supports binding parameters

:click="clicked"


@click="clicked(id)"


// 
clicked(id) {
    console.log(id)
}

of course, props can also be implemented, but the parameter id needs to be passed to the subcomponent and then called back from the subcomponent, while emit does not need it and is more flexible

.
Menu