In this example I have an object that got a name
as a string
parameter and a function that just logs this
const me = reactive({
name: "foo",
sayHi: function () {
console.log("Hi I am : ", this);
},
});
In the template I instentiate another component that after 3000ms of it creation emits an event sayHi
. This component is created twice :
<Comp :name="me.name" @sayHi="me.sayHi"/>
<Comp :name="me.name" @sayHi="me.sayHi()"/>
I kind of understand the diffrence between an event handler with and without parentheses explained here but I can’t understand why the this
in the first one is undefined
but in the second one its the object itself as I expect.
2
Answers
When
v-on
directive is provided with@sayHi="me.sayHi()"
inline expression, it’s wrapped with a function and compiled to something like:When a value is a function value like
@sayHi="me.sayHi"
, event handler is a function itself:As explained in this question,
this
context is not parent object when its method is used as a callback, and this happens when it’s passed as event handler. A function should be explicitly bound to the desired context to receive it asthis
.The difference with this question is that
sayHi
is not component method. Componentmethods
in Vue options API are internally bound to component instance, this doesn’t apply to composition API.sayHi
should refer reactive value explicitly instead of usingthis
:There’s no benefit from using
sayHi
function as a method of reactive object, it’s ignored by Vue reactivity API. Unless there are reasons forme
to be an object, e.g. it’s passed to other components, a state and function could be separated:Event call compiles differently
and