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

How to listen for a page $emit in a nuxt layout?

1个答案

1

Listening for $emit events in Nuxt.js typically refers to communication between parent and child components. Parent components can use $emit to send events, while child components can listen for these events and respond accordingly. The following provides specific steps and examples illustrating how to implement this functionality in Nuxt.js:

Step 1: Create the Parent Component

In the parent component, you may have a button or some trigger that emits events when the user interacts with it.

vue
<template> <div> <button @click="sendEvent">Click me to send an event</button> </div> </template> <script> export default { methods: { sendEvent() { this.$emit('custom-event', 'This is the data being passed'); } } } </script>

In the above example, when the button is clicked, the sendEvent method is invoked, and $emit sends a named event called 'custom-event' along with some data (in this case, a string).

Step 2: Create the Child Component

Child components need to listen for events emitted from the parent component and define how to respond to them.

vue
<template> <div> <p>Received data: {{ eventData }}</p> </div> </template> <script> export default { data() { return { eventData: '' } }, mounted() { this.$parent.$on('custom-event', this.handleEvent); }, beforeDestroy() { // Remember to remove the event listener before the component is destroyed to prevent memory leaks this.$parent.$off('custom-event', this.handleEvent); }, methods: { handleEvent(data) { this.eventData = data; } } } </script>

In this child component, we listen for the 'custom-event' event from the parent component using this.$parent.$on in the mounted lifecycle hook. The handleEvent method serves as the event handler to receive data and store it in the component's data.

Step 3: Combine Usage

Ensure that the child component is imported and registered in the parent component, and then used in the template.

vue
<template> <div> <ChildComponent /> <button @click="sendEvent">Click me to send an event</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { sendEvent() { this.$emit('custom-event', 'This is the data being passed'); } } } </script>

This way, when the button is clicked in the parent component, the child component will be able to listen for the event and respond accordingly.

Summary

This method of communication between parent and child components using $emit and event listening is a common pattern in Vue.js component communication. Nuxt.js, as a framework built on Vue, also applies this pattern. This approach allows for easy data and message passing between components while maintaining component decoupling and reusability.

2024年7月25日 17:26 回复

你的答案