Having issues with $emitting not working for parent-child components in Vue. Any ideas on what I might be doing incorrectly?

I have a login component that I need to call in the main vue component of App.vue. Within the login vue, when I click on any button, it should activate another vue component using Vue.js router to replace the login page. I have searched for solutions but haven't found any that work for me. It's frustrating because the solutions exist, but they don't seem to be effective in my case. There must be something missing, but what is it exactly? I've been trying to figure this out for two days now. One thing did work, using v-on:click.native which hides the login vue component after any click within it, but that's not the desired outcome.

Important! I am using Vue.js in a Laravel project with Laravel version 8 and Vue.js version 2

Here's the code snippet:

Login.vue

<template>
<div id="login">
    <header-nav></header-nav>
    ...
                    <form>
                       ...
                            <label>
                                <input type="email" v-model="email" name="email" class="form-control" placeholder="email">
                            </label>
                        ...
                            <label>
                                <input type="password" v-model = "password" name="password" class="form-control" placeholder="password">
                            </label>
                        ...
                            <label>
                                <input type="checkbox">
                            </label>Remember Me
                        ...
                            <input type="submit" v-on:click.prevent="login" value="Login" class="btn float-right login_btn">
                       ...
                    </form>
                <div class="card-footer">
                    <div class="d-flex justify-content-center links">
                        Don't have an account?
                        <router-link to="register" v-on:click.prevent='hideLogin'>Sign Up</router-link>
                    </div>
                    <div class="d-flex justify-content-center">
                        <a href="#">Forgot your password?</a>
                    </div>
                </div>
</div>
</template>

<script>

import HeaderNav from "../layout/HeaderNav";

export default {
    name: "Login",
    components: {HeaderNav},
    data: () => {
        return {
            email: '',
            password: ''
        }
    },

    methods:{
        login(){
            this.$store.dispatch('users/login', {email: this.email, password: this.password})
        },

        hideLogin(){
            this.$emit('hideLogin');
            console.log('Hide login');
        }
    },

    template: HeaderNav
}

</script>  

App.vue

<template>
    <div>
        <login v-if="!isHidden" v-on:hideLogin="isHidden = true"></login>
        <router-view></router-view>
    </div>
</template>

<script>
    import Login from "./auth/Login";

    export default {
        name: "App",
        components: {
            Login
        },
        data () {
            return {
                isHidden: false
            }
        },
    }
</script> 

Answer №1

According to information provided in this discussion, using click.native is necessary in order to listen for the onclick event with a router-link. For example:

<router-link to="register" v-on:click.native='hideLogin'>Sign Up</router-link>

Alternatively, you can also monitor changes within the router itself and close the modal when the route changes:

An approach to achieve this would involve updating the hideLogin logic in your Login.vue file:

Remove the click listener from the router-link and introduce a watcher for the $route

export default {
    name: "Login",
    components: {HeaderNav},
    data: () => {
        return {
            email: '',
            password: ''
        }
    },

    methods: {
        login() {
            this.$store.dispatch('users/login', {email: this.email, password: this.password})
        },

        hideLogin() {
            this.$emit('hideLogin');
            console.log('Hide login');
        }
    },

    template: HeaderNav,
    
    watch: {
        $route() {
            this.hideLogin();
        }
    }
}

By doing this, whenever you navigate to the register route (or any other route), the hideLogin method will be triggered.


Just a quick note, you can replace v-on: with @ such as @click.native.

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

Combining Vue components seamlessly with external HTML elements: A guide

Imagine working on a WordPress blog or a standard CMS that stores content using a wysiwyg editor like CKEditor. You might want to incorporate Vue components into your HTML, so you decide to add a wrapper div to your theme. Your HTML pages are enclosed by ...

Error: Attempted to search for 'height' using the 'in' operator in an undefined variable

I came across the following code snippet: $('.p1').click(function(){ var num = 10; var count = 0; var intv = setInterval(anim,800); function anim(){ count++; num--; ...

Incorporating Vuetify into a component within my Vuetify-based application

How can I properly integrate vuetify into a package used within a vuetify project? While everything seems to function correctly when serving projects, issues arise with the css/sass during project builds. Some attempted solutions include: Using vuetify ...

Having trouble passing an array from PHP to JavaScript

I'm facing an issue with the following code snippet: <?php $result = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?> <?php $resultAM = joi ...

Attempting to transmit information to database using AJAX in the context of CodeIgniter

I'm having some trouble with my AJAX setup. It doesn't seem to be posting any data to the database, despite trying various solutions I found online. That's why I've turned to this platform for help. When testing in Postman and sending ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

Inertia model - embedding a view within a model for various operations such as create, edit, and more

Currently, I am working with Laravel 9 and inertia. The project's design involves the use of modals for creating and updating functionalities. However, it appears that inertia does not offer built-in support for modals. I have come across some projec ...

Incorporate a Variety of Elements onto Your Webpage

I have developed a custom tooltip plugin using JQuery, and I am implementing it on multiple A tags. Each A tag should have a unique tooltip associated with it, so I have the following code: var $tooltip = $("<div>").attr("id", tooltip.id).attr("cla ...

using absolute URLs for image source in JavaScript

How can I output the absolute URLs of images in a browser window (e.g., 'www.mysite.com/hello/mypic.jpg')? Below is a snippet of my code: $('img').each(function() { var pageInfo = {}; var img_src = $(this).attr('s ...

Navigating array usage in Selenium IDE

I am trying to extract emails from a webpage using Selenium for future testing. I need to compare these emails with ones displayed in a selection later on. I attempted to read the emails within a while-loop but struggled with handling arrays in IDE. Unfor ...

Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab. Here's the code snippet I have written: <template> <nav class="horizontal top-border block-section"> <div class= ...

Manage YouTube video played within html code

I am working on a page that contains a YouTube video embedded in HTML. I am trying to find a way to stop the video when it is closed using the YouTube API, but so far my attempts have been unsuccessful. I have included SWFObject and jQuery in the code, yet ...

Getting the selected item from a dropdown menu and including it in an email

While working in React, I have successfully created a contact form that includes fields for name, email, and a message box. When the form is submitted, these three items are sent as expected. However, I am facing difficulty in sending a selected item from ...

Is it possible to make an element draggable after it has been prep

Seeking assistance with making a notification draggable when added to a webpage. The notifications are housed in a parent div named notification_holder Here is the structure: <div class="notification_holder"> <div class="container"><b ...

I encountered a node error 'Error: write EPIPE' while building with vue-cli-service

I encountered a node error while using Jenkins to build the project. Error: write EPIPE at process.target._send (internal/child_process.js:841:20) at process.target.send (internal/child_process.js:712:19) at callback (/home/jenkins/agent/work ...

The connection could not be established due to a cURL error 6: The host "local.crm.test.com" could

Encountering a problem shown in the screenshot specifically on my Laravel setup on my local system, utilizing a Docker container for this project. ...

Leveraging the power of axios.all for dynamic operations

Is there a way to efficiently reuse the same Vue-component for both editing and creating new users? While working with vue-router, I have implemented a beforeRouteEnter method to fetch data via API. Depending on whether an ID is set in the URL parameter, ...

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...

I aim to design a unique child window specifically for an "about" section within an electron js application on the Windows platform

I am looking to create a child browser window to showcase some key points about my application. According to the Electron JS documentation, it supports the "about" role for Mac OS but does not have built-in support for Windows. Therefore, I am in the pro ...