Alexandru Dragomir
Alexandru Dragomir

Reputation: 33

Vue 3: Emit event from child to parent

I've recently started to create an app with Vue 3 and I'm struggling with authentication when trying to emit an event from child to parent. Here's a sample of my code:

Child

<template>
  <form class="msform">
    <input @click="goToLogin" type="button" name="next" value="Login" />
  </form>
</template>

<script>
import Cookies from "js-cookie";

export default {
  emits:['event-login'],
  methods: {
    goToLogin() {
      this.$emit("event-login");
    },
  },
};
</script>

Parent

<template>
  <login v-if='loggedIn' @event-login='logIn'/>
  <div class="my-page">
    <router-view/> 
  </div>
</template>

<script>
import Cookies from "js-cookie";
import Login from '../pages/Login'

export default {
  name: "MainLayout",
  components:{
    "login":Login
  },
  data() {
    return {
      loggedIn: false,
    };
  },
  methods: {
    logIn() {
      this.loggedIn = true;
    }
  }
}

I don't know exactly why the event is not handled in the parent, can I get some help, please?

Upvotes: 3

Views: 3254

Answers (1)

Dan Knights
Dan Knights

Reputation: 8368

You're listening for the emitted event on a separate instance of login.

router-view is still just a component like any other, so try moving the handler there instead:

<template>
  <login v-if='loggedIn' />
  <div class="my-page">
    <router-view @event-login='logIn' /> 
  </div>
</template>

Upvotes: 4

Related Questions