Home > Software engineering >  How to pass a ref to a child input component with Vue?
How to pass a ref to a child input component with Vue?

Time:10-28

I'm currently trying to pass a ref to get the value of the input (base-input component) on submit. You will find below the two components. With the console.log in handleSubmit, email is always undefined.

Thanks in advance for your help.

Parent component

<template>
  <form @submit.prevent="handleSubmit">
    <div >
      <form-label forInput="email" label="Email Address" />
      <base-input type="email" name="email" ref="email" />
    </div>
  </form>
</template>

<script>

import BaseInput from "../UI/BaseInput.vue";
export default {
  components: {
    BaseInput,
  },
  methods: {
    handleSubmit() {
      const email = this.$refs.email.value;
      console.log(email);
    },
  },
};
</script>

Child Input component

<template>
  <input
    :type="type"
    :name="name"
    :ref="name"
  />
</template>

<script>
export default {
  props: ["type", "name"],
};
</script>

CodePudding user response:

first the BaseInput is spelt wrong in the template.

Instead of

<base-input type="email" name="email" ref="email" />

you need to change it to

<BaseInput :type="'email'" :name="'email'" ref="email" />

A way better approach will be to use @emit()

Child.vue

<template>
  <input
    :type="type"
    :name="name"
    @change="$emit('inputContent', Content)"
    v-model="Content"
  />
</template>

<script>
export default {
  emits: ['inputContent'],
   data() {
        return {
            Content: '',
        }
    },
  props: ["type", "name"],
};
</script>

Don't forget to declare your props as strings.

  • Related