компонент входного файла не обновляется, VueJS

#vue.js #vuejs2

#vue.js #vuejs2

Вопрос:

У меня есть некоторый код, в котором я обновляю несколько файлов с помощью пакета.

Добавление / удаление, похоже, работает, если я console.log, но если я выполняю POST-запрос, на сервере я получаю все файлы, даже если я их удаляю.

Пример: я добавляю 3 файла, удаляю 2 из них и делаю публикацию, на сервере я получаю 3 файла. (Но на консоли.журнал показывает мне, что у меня есть только 1, что правильно).

Кроме того, я нахожу эту статью, но я не уверен, что делать в моем случае.

Это сокращенная версия моего кода.

 <div id="upload-files-on-update">
    <file-upload
        :multiple="true"
        v-model="certifications"
        input-id="certifications"
        name="certifications[]"
        @input-filter="inputFilter"
        ref="upload">
        <span class="button">Select files</span>
    </file-upload>
</div>
new Vue({
    el: '#upload-files-on-update',

    data: function () {
        return {
            certifications: [],
        }
    },

    components: {
        FileUpload: VueUploadComponent
    },

    methods: {
        updateFiles(){
        let formData = new FormData();
        this.certifications.forEach((file, index) => {
            if (!file.status amp;amp; file.blob) {
            formData.append("certifications[]", 
                {
                    types: this.accept,
                    certifications_ids: this.certifications_ids,
                }
            );
            this.loadingButton = true;
            }
        });

        axios
            .post("<?php echo $link;?>", formData, {
            headers: {
                "Content-Type": "multipart/form-data"
            },
            params:{
                types: this.accept,
                certifications_ids: this.certifications_ids,
            }
            })

        },

        inputFilter(newFile, oldFile, prevent) {
            if (newFile amp;amp; !oldFile) {
                if (/(/|^)(Thumbs.db|desktop.ini|.. )$/.test(newFile.name)) {
                return prevent()
                }
                if (/.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                return prevent()
                }
            }
            if (newFile amp;amp; (!oldFile || newFile.file !== oldFile.file)) {
                newFile.blob = ''
                let URL = window.URL || window.webkitURL

                if (URL amp;amp; URL.createObjectURL) {
                newFile.blob = URL.createObjectURL(newFile.file)
                }
                newFile.pending = true;

                newFile.thumb = ''
                if (newFile.blob amp;amp; newFile.type.substr(0, 6) === 'image/') {
                newFile.thumb = newFile.blob
                }
            }
        },

        // Remove file from table
        removeFile(index) {
            this.certifications.splice(index, 1);
        },
    }
});
 

Ответ №1:

Я нашел решение этой проблемы.

 //I catch ajax request and I make sure that is the request that I want it
var self = this;
$.ajaxSetup({
        beforeSend: function (xhr,settings) {
        if(settings.type != 'POST'){
            return ;
        }

        if(settings.data.get('controller') != 'wcfm-memberships-registration'){
            return ;
        }
        
        // Here I set file input as an empty array
        settings.data.set('certifications[]',[]);
    
        // Here I add my new files from a VueJS array
        self.certifications.forEach((file, index) => {
            settings.data.append("certifications[]", file.file);
        });
        }
    });

});