Home > Back-end >  Why return from child is getting undefined in Parent in my Vue application
Why return from child is getting undefined in Parent in my Vue application

Time:07-29

I am building an Vue Application. In my child component I have a function say getName() and I am returning name but when I try to access this function in my parent I am not able to use that getting undefined. But when I emit name in the parent and Use the emit obj it is working. Can Anyone knows why I am facing this problem. Parent.vue

export default defineComponent({
  name: 'App',
  components: {
    HelloWorld
  },
  mixins: [HelloWorld],
  data() : { let value !: string return { value} }

  methods: {
    fetchval(){
      let x = this.value.getVal();
      console.log(x);
    }
  }
});
</script>

Child.vue

export default defineComponent({
  name: 'HelloWorld',
  dat(){
    let val!: string;
    return{
      val,
    }
  },
  computed: {
    value: {
      get() {
        return this.val as string;
      },
      set(newval) {
        val = newval;
      }
    }
  },
  methods: {
   getVal(){
     return this.value as string;
   }
 }
});
</script>

When I try to console.log x I am getting undefined but when i emit this.value and use it in parent working fine. What am i missing?

CodePudding user response:

The "fetchval" method in your parent is not referencing your child but the "value" property in your data function. "this" refers to your parent component. Basically, you are trying to call a "getVal" function on a string in your parent.

If you want to call a function on your child component, you need a reference to the child and call that function on that reference. You need to add a ref to your child component. If you're not familiar with refs, I suggest starting here: Template Refs

  • Related