vuejs v-model value is not updating in parent?

Viewed 3701

Using Vue3

Parent component

<template>
   <div class="col-12 col-lg-12">
        <input-image v-model="imageFile"/>                                                            
   </div>
</template>

<script>
import InputImage from "@/Pages/components/InputImage";
export default{
   components : {
       InputImage,
   },
    
   data() {
       return {
          imageFile : null,
       }
   }
}
</script>

InputImage (child) component

<template>
    <div class="form-group">
        <div
            class="base-image-input"
            :style="{ 'background-image': `url(${imageData})` }"
            @click="chooseImage"
        >
            <span v-if="!imageData" class="placeholder">Featured Image </span>
            <input
            class="file-input"
            ref="fileInput"
            type="file"
            @input="onSelectFile"
            />
        </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      imageData: null,
    };
  },

  methods: {
    chooseImage() {
      this.$refs.fileInput.click();
    },

    onSelectFile() {
      const input = this.$refs.fileInput;
      const files = input.files;
      if (files && files[0]) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.imageData = e.target.result;
        };
        reader.readAsDataURL(files[0]);
        this.$emit("input", files[0]);
      }
    },
  },
};
</script>

After selecting the file v-model (imageFile) value does not change in parent component why? Even I'm emitting input event to parent component in onSelectFile() method. I'm setting the file name here programmatically. Value changes in child component but file name is not reflected in parent component which I want as through the v-model in parent component.

1 Answers

Vue 3 changed the events for v-model updates!

Nothing major, but you define your model prop as modelValue instead of model, and your event as update:modelValue instead of input.

So, in your case, just update the child component's method from

this.$emit("input", files[0]);

to

this.$emit("update:modelValue", files[0]);

and you should be solid! https://v3-migration.vuejs.org/breaking-changes/v-model.html

Related