Home » vue » Vue pass data from compontent 1 to a method in component 2

Vue pass data from compontent 1 to a method in component 2

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a parent component and a childcomponent.
In my parent component I call a simple childcomponent-method to save an email to the email variable. But the variable email does not change.

My Parentcomponent:

import ChildComponent from "./ChildComponent";

export default {

  components: {ChildComponent},

  methods: {
    openDocument(d) {
      ChildComponent.methods.saveEmail('[email protected]');
  }
}

My Childcomponent:

<template>
  <div>
    Email: {{ email }}
  </div>

</template>

<script>


export default {

  data: function () {
    return {
      email: ''
    }
  },
  methods: {
    saveEmail(email) {
      this.email = email; // this does NOT change my email variable
    }
  }

}
</script>

Why my email variable does not change? How can I change this variable?

Answers:

In vue it is not work like that. You have to use Probs:

Parent :

<template>

    <div class="container">
        <child-component :email ="email"></child-component>   // NEW HERE
    </div>

</template>

<script>

import ChildComponent from "./ChildComponent";

module.exports = {

    data: function () {
        return {
            email:''
        }
    },

   methods: {
      openDocument(d) {
           this.email = "[email protected]"
      }
    },
}
</script>

Child component:

<template>

<div class="container">
    <h1>Profile Form Component</h1>
</div>  

</template>


<script>


module.exports = {


module.exports = {   
  props: ['email'], //NEW HERE

  created: function () {
    
    console.log(this.email) //prints out an empty string
  }
}

</script>

ATTENTION

As you I added 2 comment NEW HERE in the code , these 2 lines are really important for what you wanna do.

The code that I giving you is an example (not a complete answer) , Probs is the solution of what you asked for.

Hope it Helps <3.

###

The ChildComponent variable only holds the recipe for creating components of this type – but it does not hold your actual component. Your actual component lives inside your template – you have to add a ref attribute to it (e.g. <custom-component ref="custom" ... />) and then reference it like this.$refs.custom.saveEmail()