0

I'm programming from Vue.js and I'm trying to pass a message to the main App.vue from a component called "SignIn.vue" while using router.

In App.vue:

<template>
  <div id="nav">
    <router-link to="/signin" @do-login="doLogin">Sign in</router-link>
  </div>
</template>

<script>
export default {
  data(){
    return {
      loggedIn:false
    }
  },
  methods:
  {
    doLogin()
    {
      alert("Logging you in");
    }
  }
};
</script>

In SignIn.vue:

<template>
  <div class="signin">
    <h1>Sign in</h1>
    Username: <input type="text" />
    Password: <input type="password" />
    <button @click="logIn">Go</button>
  </div>
</template>


<script>
export default {
  methods:{
  logIn()
  {
    this.$emit("do-login");
  }
}
};
</script>

However, App.vue is not "hearing" the do-login event emitted from SignIn.vue. How can I pass messages like this while using router?

bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 2
    Did you try [attaching the event handler on the ``](/a/59836019/3634538) instead? – Yom T. Mar 26 '21 at 15:55
  • In order for App.vue to receive the event from SignIn.vue, they need to have a parent /child relationship. You would need to import and register SignIn as a child component of App. If you want the components to be siblings, and not parent/child, see [this SO question](https://stackoverflow.com/questions/38616167/communication-between-sibling-components-in-vue-js-2-0) – Tim Mar 26 '21 at 16:02

1 Answers1

0

Your approach is not the right way of doing this kind of communications. Also router-link will never handle events because once you navigate you will lose context.

As @tim said on the comment he made to your question. In order to use event handling on the App component you should have Signin as a component and not a navigation from one component to another.

If you want to have a navigation anyway, you should consider using vuex and store a prop in state that certifies that the user signed in, its a much better and cleaner approach.