0

I have created a custom input component in Vue

<template>
  <input :type="inputType" :placeholder="placeholder" v-model="vModel"  />
</template>

<script>
export default {
  name: "BaseInput",
  props: {
    inputType: String,
    placeholder: String,
    label: String,
    vModel: String,
  },
};
</script>

I don't know how exactly to pass the data that to be bounded from where we are calling the custom component

My App.vue

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <base-input inputType="text" placeholder="Enter Name" vModel="inputName">
  </base-input>
</template>

<script>
import BaseInput from "./components/BaseInput.vue";

export default {
  name: "App",
  components: {
    BaseInput,
  },
  data() {
    return {
      inputName: "",
    };
  },
};
</script>

I referred to How to enable v-model on custom component? but I couldn't understand

How can I achieve this? Thanks in advance

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
MrSrv7
  • 585
  • 8
  • 22

1 Answers1

2

The baseInput should define modelValue as prop which will be bound to the input value, emit the new typed value using this.$emit("update:modelValue",e.target.value) and add update:modelValue to emits option:

<template>
  <input :type="inputType" :placeholder="placeholder" :value="modelValue" @input="onInput" />
</template>

<script>
export default {
  name: "BaseInput",
  props: {
    inputType: String,
    placeholder: String,
    label: String,
    modelValue: String,
  }, 
 emits:["update:modelValue"],
  methods:{
    onInput(e){
      this.$emit("update:modelValue",e.target.value)
    }
  }
};
</script>

in parent component use it like :

<base-input inputType="text" placeholder="Enter Name" v-model="inputName">

If you want to use the script setup please check this answer

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • Thank You So Much. But can you explain? I mean we are not having any prop as modelValue but how we are getting its value? – MrSrv7 Jun 08 '21 at 18:47
  • you're welcome, the `v-model` directive is the equivalent of the emitted event `update:modelValue` and the prop `model` please check this https://v3.vuejs.org/guide/component-basics.html#using-v-model-on-components – Boussadjra Brahim Jun 08 '21 at 18:51