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

Does the Karma Tast Runner function on node js version 0.12.0?

I'm experiencing an issue where I have Node.js v0.12.0 installed with Karma on my OS X Yosemite, but when I try to run my test task using Gulp, it just hangs as shown in the picture. It seems like PhantomJS is not starting. Interestingly, the same cod ...

The imgAreaSelect plugin is up and running successfully. Now, I am looking to utilize the x and y coordinates to make updates to the image stored in the database. How can I

After retrieving the dimensions and coordinates from the jQuery plugin imgAreaSelect, I am looking for guidance on how to update the image in my database based on this selection. The database contains a tempImage and Image field, and my goal is to allow ...

"Server request with ajax did not yield a response in JSON format

http://jsfiddle.net/0cp2v9od/ Can anyone help me figure out what's wrong with my code? I'm unable to see my data in console.log, even though the network tab in Chrome shows that my data has been successfully retrieved. Here is my code snippet: ...

Unfortunately, my deployment on Vercel encountered an error related to npm. Specifically, the error involved the extraction of a file from the tarball for node-v18.15

Trying to deploy my GitHub project on Vercel. The project is built using Vue. However, when building the project on Vercel, I encountered numerous errors like this: npm ERR! gyp verb extracted file from tarball node-v18.15.0/include/node/openssl/archs/VC-W ...

Navigating on Vue with server-side rendering and Laravel

Currently, I am delving into Vue and facing a challenge setting it up as the complete front-end with Laravel. In my current setup, I have created a personal blog for testing purposes using Laravel with Blade engine and incorporating some Vue components whi ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

Cascading MVC 2 Dropdown menus

I am trying to bind a dropdown based on the change of another dropdown, but I keep getting an "Undefined" error. Here is my code snippet: <select id="BreakOutValue" class="input1_drop" onchange="onChange()" ></select> <%:Html.DropDownList( ...

Retrieve information stored within an object's properties

Possible Duplicate: Accessing a JavaScript Object Literal's Value within the Same Object Let's take a closer look at this JavaScript object var settings = { user:"someuser", password:"password", country:"Country", birthplace:countr ...

What is the most effective way to utilize an existing table in MySQL with a TypeORM entity?

While working with typeorm to connect to a mysql db, I encountered an issue where my table definition was overwriting an existing table in the database. Is there a way for me to use the entity module to fully inherit from an existing table without causin ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

Developing a webpage that navigates seamlessly without the hassle of constantly refreshing with

I am in the process of creating a website that is designed to run everything within the same file, but I am unsure about how to locate study materials for this project. For example: In a typical website scenario -> If I am on index.php and I click on the ...

Changing a URL parameter based on the element's width is a simple task when

I'm trying to display elements on a page by replacing a string in the URL parameter with the width of each element of a certain class. I'm new to JavaScript, so any help would be appreciated! Here's an example of the HTML for objects on the ...

Is there a simple and efficient method to transition the loading of a regular website to AJAX for the entire site?

Is it feasible to easily and quickly change all links on a website to load the URL that the user clicked via AJAX, rather than refreshing the webpage? My website currently has standard links, but in order to create a mobile application for iPhone, I need ...

JavaScript can be used to create a fullscreen experience without any toolbars, scrollbars, and the like, without having

Is there a way for me to expand the current window I am using to fullscreen mode and eliminate all toolbars? ...

The HTML Bootstrap collapse feature is not functioning correctly upon the initial button press

Could you assist me with implementing a bootstrap and javascript collapse feature? I have two collapsible cards. The first card should be visible initially, but then switch to the second card when clicked on a link. However, upon the first click, both card ...

Generating dynamic divs in parallel

Despite encountering numerous posts related to the issue at hand, none of them have solved my specific problem. I am aiming for 3 divs to display in each row, but the current code is causing each div to show up on a new line vertically: JQuery ...

Child element casting shadow over parent element

I am currently using box shadow for both the parent (.map) and child (.toggle-button): .map { position: fixed; top: 20px; right: 0; width: 280px; height: 280px; z-index: 9999; box-shadow: 0px 1px 6px 0px rgba(0,0,0,0.3); } .map ...