@lemonlimelike

Как объединить два метода?

Метод uploadImage:

uploadImage(event) {

			    const URL = 'http://foobar.com/upload'; 

			    let data = new FormData();
			    data.append('name', 'my-picture');
			    data.append('file', event.target.files[0]); 

			    let config = {
			      header : {
			        'Content-Type' : 'image/png'
			      }
			    }

			    axios.put(
			      URL, 
			      data,
			      config
			    ).then(
			      response => {
			        console.log('image upload response > ', response)
			      }
			    )
			 }

отвечает за отправку файла на сервер, вот input Для него:

<input type="file" accept="image/*" @change="uploadImage($event)" id="file-input">

А вот метод для создания записи:

create: function(){
    				axios.post('/api/crud',{
    					name: this.name,
    					keywords: this.keywords,
    					title: this.name
    				}).then(response =>{
    					console.log(response)
    					location.href = '/crud';
    				}).catch(error =>{
    					console.log(error.response)
    				});
    			}

Как эти два метода объединить, чтоб они срабатывали по клику на одну кнопку?
  • Вопрос задан
  • 283 просмотра
Решения вопроса 2
0xD34F
@0xD34F Куратор тега Vue.js
Файл, выбираемый через input, сделать свойством компонента, обновлять по событию change:

data: () => ({
  file: null,
  ...

<input type="file" accept="image/*" @change="file = $event.target.files[0]">

В объединённом методе при собирании formData вместо объекта события доставать файл из упомянутого выше свойства:

methods: {
  uploadAndCreate() {
    const data = new FormData;
    data.append('name', 'picture');
    data.append('file', this.file);

    axios.put(... // запрос из uploadImage

    axios.post(... // запрос из create
  },
  ...
Ответ написан
Комментировать
shahob
@shahob
Программист
<input type="file" accept="image/*" @change="handleChange($event)" id="file-input">
<button v-on:click.prevent="handleSend">Отправить</button>

new Vue({
    el: '#app',
    data: {
        name: 'John Doe',
        keywords: 'key',
        form: new FormData()
    },
    methods: {
        handleSend: function () {
            // upload image
            axios.put(
                '/upload',
                this.form, {
                    header: {
                        'Content-Type': 'image/png'
                    }
                }
            ).then(response => {
                console.log('image upload response > ', response);
            });

            // send form
            axios.post('/api/crud', {
                name: this.name,
                keywords: this.keywords,
                title: this.name
            }).then(response => {
                console.log(response);
            }).catch(error => {
                console.log(error.response);
            });

        },
        handleChange: function (event) {
            this.form.append('name', 'my-picture');
            this.form.append('file', event.target.files[0]);
        },
    }
});
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы