Как передать ввод объекта и обновить данные в одном всплывающем окне, используя Vue-SweetAlert2 - PullRequest
0 голосов
/ 02 июля 2019

В настоящее время я пытаюсь создать всплывающее окно, в котором пользователь должен заполнить свою личную информацию, как показано в следующем коде и прикрепленном изображении.

<template>
      <v-btn class="create-button" color="yellow" @click="alertDisplay">Create</v-btn>

    <br/>

    <p>Test result of createCustomer: {{ createdCustomer }}</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        createdCustomer: null
      }
    },
    methods: {
      alertDisplay() {
        const {value: formValues} = await this.$swal.fire({
            title: 'Create private customer',
            html: '<input id="swal-input1" class="swal2-input" placeholder="Customer Number">' +
                '<select id="swal-input2" class="swal2-input"> <option value="fi_FI">fi_FI</option> <option value="sv_SE">sv_SE</option> </select>'
                 + 
                '<input id="swal-input3" class="swal2-input" placeholder="regNo">' +
                '<input id="swal-input4" class="swal2-input" placeholder="Address">' +
                '<input id="swal-input5" class="swal2-input" placeholder="First Name">' +
                '<input id="swal-input6" class="swal2-input" placeholder="Last Name">'
                ,
            focusConfirm: false,
            preConfirm: () => {
                return [
                    document.getElementById('swal-input1').value,
                    document.getElementById('swal-input2').value,
                    document.getElementById('swal-input3').value,
                    document.getElementById('swal-input4').value,
                    document.getElementById('swal-input5').value,
                    document.getElementById('swal-input6').value
                ]
            }
        })
        if (formValues) {
            this.createdCustomer = this.$swal.fire(JSON.stringify(formValues));
            console.log(this.createdCustomer);
        }   
      }
    }
  }
</script>

multiple inputs

Таким образом, я могу позволить пользователю заполнить несколько полей, но я хочу сохранить «Адрес» в форме объекта, а не просто строку.

"address": {
    "street": "string",
    "city": "string",
    "country": "string",
    "region": "string",
    "zipCode": "string"
}

Мне удалось изменить один из 6 входов на тип "select" вместо типа "input", который просто позволяет пользователям писать некоторый текст, но когда дело доходит до типа объекта, который состоит из нескольких строк, как указано выше, я не надену не знаю, как это сделать, когда мне нужно использовать параметры HTML и preConfirm.

Как я могу это сделать? Можно ли вообще сохранить «адрес» как объект?

[ОБНОВЛЕНО]

То, что я пытаюсь сделать, - это позволить пользователю заполнить каждую из "улиц", "городов", "стран", "регионов", "zipCode" по отдельности, как показано на рисунке ниже,

enter image description here

и сохраните их как «адресный» объект, как показано ниже

"address": {
    "street": "string",
    "city": "string",
    "country": "string",
    "region": "string",
    "zipCode": "string"
}

[ОБНОВЛЕНО (Версия2]

v-модель не работает

async alertDisplay() {

        const {value: formValues} = await this.$swal.fire({
            title: 'Create private customer',
            html: '<input id="swal-input1" class="swal2-input" placeholder="Customer Number">' +
                '<select id="swal-input2" class="swal2-input"> <option value="fi_FI">fi_FI</option> <option value="sv_SE">sv_SE</option> </select>'
                 + 
                '<input id="swal-input3" class="swal2-input" placeholder="regNo">' +
                '<input v-model="createdCustomer.address.street" id="swal-input4" class="swal2-input" placeholder="Address (street)">' +
                '<input v-model="createdCustomer.address.city" id="swal-input5" class="swal2-input" placeholder="Address (city)">' +
                '<input v-model="createdCustomer.address.country" id="swal-input6" class="swal2-input" placeholder="Address (country)">' +
                '<input v-model="createdCustomer.address.region" id="swal-input7" class="swal2-input" placeholder="Address (region)">' +
                '<input v-model="createdCustomer.address.zipCode" id="swal-input8" class="swal2-input" placeholder="Address (zipCode)">' +
                '<input id="swal-input9" class="swal2-input" placeholder="First Name">' +
                '<input id="swal-input10" class="swal2-input" placeholder="Last Name">'
                ,
            focusConfirm: false,
            preConfirm: () => {
                return [
                    document.getElementById('swal-input1').value,
                    document.getElementById('swal-input2').value,
                    document.getElementById('swal-input3').value,
                    document.getElementById('swal-input4').value,
                    document.getElementById('swal-input5').value,
                    document.getElementById('swal-input6').value,
                    document.getElementById('swal-input7').value,
                    document.getElementById('swal-input8').value,
                    document.getElementById('swal-input9').value,
                    document.getElementById('swal-input10').value
                ]    

            }
        })
        if (formValues) {
            this.createdCustomer = formValues;
            console.log('the content of this.createdCustomer');
            console.log(this.createdCustomer);
            console.log('the content of this.createdCustomer.address');
            console.log(this.createdCustomer.address);
        }   
      }

Выход

enter image description here

Но я хочу, чтобы это было похоже на

Test result of createCustomer: [ "JS1", "fi_FI", "123ABC", {"stackoverflow st 12", "San Francisco", "USA", "California", "12345"}, "Shinichi", "Takagi" ]

Ответы [ 2 ]

0 голосов
/ 03 июля 2019

Мне удалось найти решение этой проблемы, поэтому я выложу ответ самостоятельно.

Корень проблемы оказался в одной строке this.createdCustomer = formValues; в детали

if (formValues) {
            this.createdCustomer = formValues;
            console.log('the content of this.createdCustomer');
            console.log(this.createdCustomer);
            console.log('the content of this.createdCustomer.address');
            console.log(this.createdCustomer.address);
        }   

моего исходного поста с вопросом.

Поскольку пользовательские входы хранились как 10 отдельных входных данных типа примитивов вместо «адреса» формы объекта, который содержит несколько строк, это был массив строк, который был назначен на this.createdCustomer из formValues.

Чтобы решить эту проблему, я сделал следующие две вещи.

  1. Объявить createdCustomer в виде объекта
  2. Назначайте каждое значение formValues ​​по одному, ссылаясь на его порядковые номера ( ← это то, чего я так долго не понимал )

Что касается первого пункта, я объявил createdCustomer следующим образом.

data() {
      return {
        createdCustomer: {
          customerNumber: null,
          locale: null,
          regNo: null,
          address: {
            street: null,
            city: null,
            country: null,
            region: null,
            zipCode: null
          },
          firstName: null,
          lastName: null
        }
      }
    },

А что касается второго пункта, я ссылался на индексы formValues ​​по одному, как это.

if (formValues) {
            //this.createdCustomer = formValues;   // this one line overwrote the entire createdCustomer object, which was the root of the problem
            this.createdCustomer.customerNumber = formValues[0];
            this.createdCustomer.locale = formValues[1];
            this.createdCustomer.regNo = formValues[2];
            this.createdCustomer.address.street = formValues[3];
            this.createdCustomer.address.city = formValues[4];
            this.createdCustomer.address.country = formValues[5];
            this.createdCustomer.address.region = formValues[6];
            this.createdCustomer.address.zipCode = formValues[7];
            this.createdCustomer.firstName = formValues[8];
            this.createdCustomer.lastName = formValues[9];

            console.log('the content of this.createdCustomer.address');
            console.log(this.createdCustomer.address);

            console.log('the content of this.createdCustomer.address.street');
            console.log(this.createdCustomer.address.street);

        }   

И теперь, когда «адрес» передается в форме «адресного» объекта, и вывод такой же, как и ожидалось.

Test result of createCustomer: { "customerNumber": "JS1", "locale": "fi_FI", "regNo": "123ABC", "address": { "street": "stackoverflow st 12", "city": "San Francisco", "country": "USA", "region": "California", "zipCode": "12345" }, "firstName": "Shinichi", "lastName": "Takagi" }

successful

0 голосов
/ 02 июля 2019

Вы можете использовать v-model.Таким образом, при изменении значения на входе значение объекта адреса также изменится.

<input v-model="address.street">
<input v-model="address.city">
<input v-model="address.country">
<input v-model="address.region>
<input v-model="address.zipCode">

См. Этот пример https://jsfiddle.net/greenfoxx/bo8cfxqz/5/

Ссылка для v-model https://vuejs.org/v2/guide/forms.html

...