Question presented to candidate: "A form needs a submit button that must not reload the page, a search box that reacts to Enter, and a card whose inner buttons must not trigger the card click. How do you handle these events in Vue?"
What a strong answer should cover:
v-on:eventor the shorthand@eventattaches a listener; the value is a method handler (@click="save", receives the native event) or an inline handler (@click="save(item.id)", use$eventto get the event).- Event modifiers replace boilerplate:
.prevent(preventDefault),.stop(stopPropagation),.self,.once,.capture,.passive. - Key modifiers (
@keyup.enter,.esc,.tab,.delete, arrow keys, or any kebab-caseKeyboardEvent.key), system modifiers (.ctrl,.alt,.shift,.meta),.exactand mouse buttons (.left,.right,.middle). - Modifiers can be chained and order matters (
.prevent.selfdiffers from.self.prevent). - On components,
@eventlistens to events the child emits (declared withdefineEmits); Vue 2.nativeno longer exists. - Template listeners are attached directly to each element (no global delegation) and go away with the element when it is removed; listeners you add yourself to
windowordocumentmust be removed inonUnmounted.
Clarifying questions expected:
- "Is this a native DOM element or a custom component emitting events?"
Code / implementation expected: Yes. A template showing @submit.prevent, @keyup.enter and @click.stop.