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

Exploring the process of iterating through JSON data using JSON.parse

After making a request to my Django server for data, I utilized JSON.parse to convert the data into a JSON object. My goal is to iterate through each attribute of the object's field and execute the function createDiv on each one. function load_blog( ...

Sending an Ajax request to a nearby address

I'm feeling a bit lost on how to achieve this task. I've been searching online, but it seems like my search terms may not have been quite right. My goal is to set up a RESTful api. $.ajax({ type: "POST", url: "https//my.url/", data: ...

jQuery problem: Unable to access a property that is undefined

After testing my code on JSfiddle, I noticed that it works perfectly. However, when I try to implement it on a webpage with jQuery already loaded in the DOM, I encounter a console error, shown in the screenshot. I am certain that the iframe selector I am ...

Responsive jQuery drop-down navigation menu for touchscreen devices struggles with hiding one menu item while clicking on another

I'm currently working on implementing a dropdown navigation menu for touch devices utilizing jQuery. I have managed to successfully hide dropdowns when tapping on the menu item title or outside the navigation area. However, I am facing an issue where ...

Encountering an E2BIG error when running vue-cli-service build

Currently, I am working on a Vue.js 2 application development project using Ubuntu 20.04.1 LTS as my operating system. Here is how my package.json file is structured: { "name": "my-app", "version": "0.0.1", &qu ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...

Information vanishes as the element undergoes modifications

I am currently working with a JSON file that contains information about various events, which I am displaying on a calendar. Whenever an event is scheduled for a particular day, I dynamically add a div element to indicate the presence of an event on the c ...

Error encountered in amCharts Serial Chart when data parsing is enabled with the setting "parseDates": true which resulted in the failure to display data

Using Spring as a webservice, I received a JSON response with stock data: [ { "date": "2016-04-17", "open": 1085.0, "high": 1092.2, "low": 1072.0, "close": 1088.3, "volume": 54100, "value": 1088.3 }, { "date": "2016-04-14", "open": 1081. ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

The transitions in Vue do not seem to be functioning properly when used with router-link and $router

I have the following structure in my App.vue file: <script setup> import { RouterView } from "vue-router"; </script> <template> <RouterView v-slot="{ Component }"> <transition :name="fade" mod ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResultSe ...

Is there a way to include a React component within the setContent method of Leaflet?

Is there a way to trigger a React JS component in setContent? I am looking for a solution to add a button within a popup Leaflet, which when clicked will call a React component. While I am aware of the "reactDomserver.rendertostring" method to co ...

Compatibility issues between XMLHttpRequest and curl

Today, I am attempting to create a small XHR in JavaScript, Java, and C#, but it's not working for some reason... Below is the code snippet: var xhr = new XMLHttpRequest(); function init(){ xhr.open("POST","http://www.opsu.gob.ve/portal/controles/ ...

Issue: Package 'cairo' not located on EC2 Bitnami MEAN server

Setting up my MEAN application on a Bitnami server has been quite a challenge. During the installation of dependencies, I encountered an error that I just can't seem to resolve. Despite following the instructions provided in the error message, I am st ...

I want the name to be retained in storage to prevent the item from being mistakenly renamed when deleted based on its index

After pressing the "add layer" button in the box shadow generator, a new layer is added. For example, let's say I have added 3 layers (Layer 1, Layer 2, Layer 3) and then deleted Layer 2. After deletion, the remaining Layers are Layer 1 and Layer 3, b ...

Changing the prototype of a generator function

TL;DR I am looking to enhance a generator function instance by adjusting its prototype, specifically the object received when calling a function*. Imagine I have a generator function: function* thing(n){ while(--n>=0) yield n; } Next, I create a ...

directive does not execute when the <Enter> key is pressed

I recently came across a helpful post on Stack Overflow about creating an Enter keypress directive. After following the instructions, here is my JavaScript code that replicates the functionality: JavaScript var app = angular.module('myApp', [] ...

Leverage Jquery within the div element to manipulate the data retrieved from a post ajax request

On my one.jsp page, I have the following post code: $.post("<%=request.getContextPath()%>/two.jsp", { vaedre: fullDate} ,function(result){ $("#theresult").append(result); }); This code generates the followi ...

Warning: Shadcn-UI Form Alert - An element is converting an uncontrolled input to controlled mode

Throughout the course of this project, I found myself repeatedly using const [fileNames, setFileNames] = useState<string[]>([]); and logging the state with console.log(fileNames). However, every time I clicked on the parent element, an empty Array e ...