2

I have a custom input component that generally works well. But since yesterday I want to pass to it a value from the parent component in certain cases (namely if a cookie is found for that field, pre-fill the field with the cookie value).

Parent component (simplified):

<custom-input
  v-model="userEmail"
  value="John Doe"
/>

But for a reason I cannot comprehend, the value prop doesn't work. Why not?

My custom input component (simplified):

<template>
  <input
    v-bind="$attrs"
    :value="value"
    @blur="handleBlur"
  >
</template>

<script>
export default {
  inheritAttrs: false,
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  mounted () {
    console.log(this.value) // displays nothing, whereas it should display "John Doe"
  },
  methods: {
    handleBlur (e) {
      this.$emit('input', e.target.value)
    }
  }
}
</script>
drake035
  • 3,955
  • 41
  • 119
  • 229

1 Answers1

1

value prop is used with the emitted event input to do the v-model job, so you should give your prop another name like defaultValue to avid this conflict:

<custom-input
  v-model="userEmail"
  defaultValue="John Doe"
/>

and

<template>
  <input
    v-bind="$attrs"
    :value="value"
    @blur="emitValue($event.target.vaklue)"
  >
</template>
<script>
export default {
  inheritAttrs: false,
  props: {
    value: {
      type: String,
      default: ''
    },
   defaultvalue: {
      type: String,
      default: ''
    },
  },
  mounted () {
    this.emitValue(this.defaultValue) 
  },
  methods: {
    emitValue(val) {
      this.$emit('input', val)
    }
  }
}
</script>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • Thanks! How do I apply `defaultValue` to the field so users can see it though? Also I still don't understand why my code doesn't work, why is `value` empty? – drake035 Jun 29 '21 at 10:38
  • 1
    You're welcome bro, As I said `value` prop in this case is reserved and it's used with `input` event to do `v-model` job, to apply it I think you could try out `this.$emit('input', defaultValue)` inside mounted hook – Boussadjra Brahim Jun 29 '21 at 10:44