props in vue
Can someone just confirm if my understanding of how we listen to events in child components occur in vue pls. From what I've understood, we need to define an emit event using
defineEmits. So based on the second code snippet above, when we click on button, this emits the custom event.
Now, how does our parent "listens" to the event emitted by its child component?
I read this:
So this mean if we have an @custom-event instance on our child component, like <Child @someEvent />, our parent is listening to "someEvent"?
How does it do that though? I would expect that we would define something on the parent component, like making as if our parent knows what to expect from the child, no?2 Replies
You are telling the parent what event to expect from the child by putting
@someEvent="doSomething(n)" in the component <Child @someEvent="doSomething(n)" /> . I am not sure how it works under the hood. You might be thinking of how you have to add event listeners to DOM elements so that element hears the event. Maybe Vue abstracted that away, but then again this is all virtual DOM.
It has been a couple of years since I worked in Vue reguarly, but I had over 7 years experience with Vue 2 and limited Vue 3. Things don't seem to have changed too much. Composition API is the same as Options API just a different flavor.Your code looks correct to me. Only thing i'd change is create a dedicated handler function for your event listener
@enlarge-text="handleEnlargeText" to keep as much logic out of the template as possible. just a cleanliness pattern though
Passing events around like this is quite annoying. I would actually solve this with a store. Assuming you only have one blog post visible at once, you can elevate the state of your font size into a global store. The store can then be used by any component and you don't need to connect events like that
Any state that should exists in the context of the whole application and not just one ui component, like user preferences, should be stored in stores
But I understand that this was maybe just an example for how events work. In which case I think you got it right