乐闻世界logo
搜索文章和话题

Why v-on:click does not work on a vue component?

1个答案

1

In Vue.js, the v-on directive is used to listen for DOM events, such as user click events. When you use v-on:click or its shorthand form @click on native HTML elements, it works as expected because it binds a click event listener to that element. However, when you apply the same directive to a Vue component, the behavior differs. The v-on listener on a component does not directly listen for native events on the root element of the child component; instead, it listens for custom events emitted by the child component. Vue component instances do not automatically treat their event listeners as native DOM event handlers. This is because the root element of a component can be any element or another component, and Vue does not apply special handling to it. If you want to listen for a native event (such as a click event) on a component, you need to use the .native modifier to instruct v-on to listen for native events, as shown below:

vue
<!-- MyComponent.vue --> <template> <button @click="$emit('click')">Click me</button> </template> <script> export default { emits: ['click'] }; </script>
vue
<!-- ParentComponent.vue --> <template> <my-component @click.native="handleClick"></my-component> </template> <script> export default { methods: { handleClick() { console.log('Button clicked!'); } } }; </script>

In this example, we have a child component MyComponent that listens for click events on a button and emits a custom event named click when clicked. In the parent component, we use the .native modifier to listen for this native click event. However, note that starting from Vue 3, the .native modifier has been removed because Vue 3 advocates for components to explicitly define and emit their own custom events. Therefore, in Vue 3, you should explicitly emit custom events from the child component using $emit, and listen for these events in the parent component rather than native events. If you do need to listen for native events on the root element of the child component in the parent component, you should bind a native event listener inside the child component and trigger a custom event when necessary.

2024年6月29日 12:07 回复

你的答案