简体   繁体   中英

VueJS - Update parent values from emit with parameters?

I don't really know how to put it but i'll explain:

I have a form where the user can upload an image. The upload image goes as followes

<input id="visualisation_upload" @change="onThumbnailChanged" name="visualisation_upload" accept="image/*" type="file" class="sr-only">

onThumbnailChanged (event) {
    const file = event.target.files[0];
    this.fields.thumbnail = file;
    this.fields.thumbnailPreview = URL.createObjectURL(file);
},

I want to show the user which files has been uploaded and let them delete the files if they so desire. For that exact purpose I use a component called uploadedFiles

I call the component like follows:

<uploadedFiles v-if="this.fields.thumbnail" :file="this.fields.thumbnail" :preview="this.fields.thumbnailPreview" @update-images="updateFiles"></uploadedFiles>

Within the uploadedFiles component I have a click Event that is supposed to empty both props within uploadedFiles AND the props that were passed to the component. When I try do to it directly within the component like this (Which you shouldn't do) I of-course get Avoid Mutating a Prop Directly :

deleteFiles() {
    this.file = ''
    this.preview = null
}

Within the parent component I have a method there I would like to empty the values like this

<a @click="$emit('update-images', file, preview), file = '', preview = null" class="hover:text-gray-900 cursor-pointer"></a>

updateFiles: function(file, preview) {
    file = ''
    preview = null
},

But I can't seem to make it work. I am trying to make the component dynamic so I don't have to create the method in each component.

I don't know if i am making any sense. Point is, when clicked on the button. Empty both this.fields.thumbnail & file from the component. How can I accomplish this?

You can emit update:xxx events and then use xxx.sync modifier in the parent ( https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier ):

<uploadedFiles 
  v-if="this.fields.thumbnail" 
  :file.sync="this.fields.thumbnail" 
  :preview.sync="this.fields.thumbnailPreview" 
/>
deleteFiles() 
{
    this.$emit('update:file', '');
    this.$emit('update:preview', null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM