简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM