David Meinke
David Meinke

Reputation: 43

Emit to Parent triggers method but not value

When a user logs in we return the user_name and $emit it from the login.vue component to the App.vue component and to trigger an updateUser() method but the value is null even though I can alert or log the user_name

Tried to define the user_name a couple different ways user_name and this.user_name

login.vue -- login method

await this.$apollo.mutate({mutation: LOGIN, variables:{username: 
this.username, password: this.password}})
.then((result) => {
const user_name = result.data.login.user.User_Name
alert(user_name)
this.$emit('displayUser', user_name) 

App.vue

   <v-list-item-title class="title" v-if="user_name" v-bind:user_name="user_name" > 
    {{user_name}}
    <v-list-item-subtitle>

Where the login.vue is contained in the app.vue component

  <v-content>
    <router-view v-on:displayUser="updateUser(user_name)"></router-view>
    </v-content>  

Method - the alert is triggered with undefined


 updateUser(userN){
  alert(userN)
  if (userN === 'hide'){
    this.user_name = ''
   }
   else{
   this.user_name = userN;
   }
}

I can get the alert to pop up in the updateUser method but the value is null or undefined

Upvotes: 0

Views: 151

Answers (1)

rideron89
rideron89

Reputation: 531

It is likely you need to replace your <router-view> code with this:

  <v-content>
    <router-view v-on:displayUser="updateUser"></router-view>
  </v-content>

Note that I am no longer passing user_name in the event handler. That is because user_name is not available in your template.

You are saying On 'displayUser', call the 'updateUser' with the 'user_name' variable. But user_name is not known to your App component.

But what you mean to actually say is On 'displayUser', call the 'updateUser' method with whatever event parameters are sent back.


You may also specify the event parameters by passing $event like so:

<v-content>
  <router-view v-on:displayUser="updateUser($event)"></router-view>
</v-content>

Docs: https://v2.vuejs.org/v2/guide/events.html#Methods-in-Inline-Handlers

Upvotes: 1

Related Questions