Guide on creating event hooks within VUE 2.0 component connections

I have successfully created two dynamic components. Now, I am looking to trigger the "logThat(someObj)" method of component-two using events: $emit/$on with the arguments being passed as shown in this code snippet:

Vue.component('component-one', {
    template: '#template-a',
    methods: {
        onClick() {
            const someObj = {
                foo: "foo",
                bar: "bar"
            }

            vm.$emit('selected', someObj)
            vm.currentView ='component-two';
        }
    }
});

//Stuck on this??
/*vm.$on('selected', (someObj) => {
    this.logThat(someObj)
})*/

Vue.component('component-two', {
    template: '#template-b',
    methods: {
        onClick() {
            vm.currentView ='component-one';
        },
        logThat(someObj) {
            console.log(someObj);
       }
    }
});

https://jsfiddle.net/wanxe/yuh71e1o/

If you have any insights on how to tackle this situation, your input would be greatly valued :)

Answer №1

According to the documentation, the recommended approach is to utilize Non-parent-child communication.

However, in your current scenario, this method will not be effective. The issue lies in the creation and destruction of components 'one' and 'two' as you navigate back and forth.

I have updated your jsFiddle: https://jsfiddle.net/mani04/yuh71e1o/4/. The key changes are:

Event bus setup:

var bus = new Vue();

Emitting event from component-one:

bus.$emit('selected', someObj);

Listening for event in component-two:

created: function() {
   console.log("Created component-two, listening for 'selected' event");
   bus.$on('selected', this.logThat);
}

If you check the developer console logs, you will notice that multiple instances of component-two are created, with the old ones still active due to incomplete destruction.

To resolve this issue, it is advisable to avoid dynamic components and instead have both 'component-one' and 'component-two' present simultaneously in your root template. You can then show or hide them based on the desired view using v-show (avoid v-if which results in instance destruction). Subsequently, employ the event bus for communication following the guidelines outlined in the Non-parent-child communication section of the documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Have I got it all wrong with the way Controllers communicate with Services and how I conduct unit testing?

Currently, I am in the process of developing an AngularJS application and I want to ensure it follows best practices. When making external API calls using either $resource or $http, I always do this within a separate Service or Factory. However, I am unsur ...

Customizing Tailwind CSS Classes within a Flexible VueJS Component

I have developed a custom VueJS button component utilizing TailwindCSS. My objective is to furnish this button component with predefined styles by applying tailwindcss classes, while also allowing for the flexibility to override these styles when necessary ...

Unraveling the Mysteries of Node.js Application Logging

We've been having smooth sailing with our Kube cluster on AWS, but there seems to be a recurring issue with our Node app crashing and generating repetitive logs from our instances... I've scoured the internet for solutions but haven't had m ...

How to use JavaScript regular expressions to verify that an input contains more than zero characters

Can someone help me with a simple regex issue? I've tried searching online but couldn't find a suitable example. I'm struggling with regex and just need to ensure that an input contains more than 1 character (i.e. is not blank). My code uses ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

Determining the Next Available Date from JSON Data

I have a task of using a JSON response from the Eventbrite API to showcase the upcoming event tour date. The goal is to automatically calculate this date based on the current time, identifying the next event after the current moment. Below is the JSON res ...

Show Particular Outcome at the Beginning of Array in ReactJS

I am working with an array of data that contains a list of names, and I need to sort it so that a specific name ("Fav Team") always appears at the top of the list. The array has two fields, homeTeamName and awayTeamName, that may contain this value. How ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

What are the best techniques for creating animations in AngularJS?

I've been trying to figure out how to animate in AngularJS by searching online, but I haven't found a perfect solution yet. html <span class="sb-arrow down" ng-click="hideSampleList($event)"></span> ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Re-rendering multiple components with the new `use` feature in React version 18.3.0

When trying to fetch and use data using React 18.3.0, I encountered an issue with multiple re-rendering. react: 18.3.0-canary-3ff846d10-20230724 next: 13.4.12 The code for SuspenseTest component is causing multiple console outputs (about 5 to 8 times) be ...

Encountering numerous errors when attempting to incorporate lottie-web into my JavaScript file

I am in the process of creating a unique audio player for my website utilizing HTML, CSS, and JavaScript. I encountered some challenges while trying to get it to work effectively on Codepen as well as my text editor. The animations were not functioning pro ...

Tips for properly aligning an image within an owl carousel

Currently, I am attempting to center a small image within the owl carousel. While I have managed to center it when it's active and in the center, I'm encountering issues when the item no longer carries the "center" class. You can access Owlcarou ...

How to extract the complete URL from the API endpoint in nextjs

I'm curious if there is a way to fetch the complete URL of the current request within the API route (pages/api/myapi). The only response I have found that comes close to what I need is the req.headers.referer, but I am uncertain if this value will alw ...

What could be the reason for the malfunction of this angular binding?

Looking at the HTML below: <input type="checkbox" name="person" [(ngModel)]="person.selected" /> This input is part of a ngFor loop. Testing has revealed that despite some values of selected being true and others false, all checkboxes appear check ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

Is the PHP Ajax parameter missing during the upload process?

I'm attempting to do a simple upload, but I seem to be struggling. It could be that I'm not understanding it properly, or perhaps it's just too late at night for me to figure it out. After doing some research, I came across this example on ...

How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which ...

Running time assessment for JavaScript executions

My current focus is on the execution time of JavaScript programs. Upon running them with nodejs/v8, I have noticed that the time command in the shell produces inconsistent results for execution times. Is there a method to sandbox the execution of these pr ...

Using Express Router to call a dynamic route instead of the intended named route

I'm currently developing an API using Express.js, implementing routes and controllers. Within my api.js file, I have the following setup: const app = express() app.use('/clients', clients) Then, in my router/client.js file, I specify the e ...