При сохранении объекта с использованием сообщения ax ios данные из v-select не сохраняются в базе данных Vuejs, Vuetify datatable - PullRequest
0 голосов
/ 02 мая 2020

У меня проблема с тем, что при использовании метода записи с использованием осей мне нужно будет отправлять данные в следующем формате json:

{
  "id":"1",
  "firstName":"Faabio",
  "lastName":"Mendes de Jesus",
  "phone":"11941649284",
  "mobilePhone":"11941649284",
  "email":"art7design2013@gmail.com", 
  "gender":
          {"name":"masculino"}
}

Однако при сохранении секс сохраняется только в спереди, но он не сохраняется в базе данных, мой console.log записывает следующие ситуации: В объекте: config данные верны и связаны с полом, но в config: данные больше не отображаются, что указывает на то, что что-то отсутствует для сохранения данных, и я схожу с ума по этому, следуйте консоли:

image

Эта строка, которая была сохранена, в формате json , пол становится нулевым, и изображение таблицы данных с пустым полем:

{
  "id":"3",
  "firstName":"ana",
  "lastName":"lucia",
  "phone":"1188888888",
  "mobilePhone":"1188888888",
  "email":"analu@gmail.com",
  "gender":null
}

image

Мой файл. vue

<template>
    <v-data-table
      :headers="headers"
      :items="clients"
      sort-by="firstName"
      class="elevation-2"
    >
      <template v-slot:top>
        <v-toolbar flat color="white">
          <v-icon medium>mdi-account-supervisor</v-icon>
            <v-toolbar-title> Clients</v-toolbar-title>
          <v-divider
            class="mx-4"
            inset
            vertical
          ></v-divider>
          <v-spacer></v-spacer>
          <v-dialog v-model="dialog" max-width="600px">
            <template v-slot:activator="{ on }">
                <v-btn 
                color="blue" 
                dark class="mt-6 mb-4" 
                v-on="on"
                rounded
                ><v-icon medium>mdi-plus</v-icon>Add new</v-btn>
            </template>
            <v-card>
              <v-card-title>
                <span class="headline">{{ formTitle }}</span>
              </v-card-title>

              <v-card-text>
                <v-container>
                  <v-form>
                    <v-row>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.firstName" label="First Name"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.lastName" label="Last Name"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.email" label="E-Mail"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.phone" label="Phone"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <v-text-field v-model="editedItem.mobilePhone" label="Mobile Phone"></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" md="12">
                        <!-- select options-->
                        <v-select
                          label='Gender'
                          v-model='editedItem.gender'
                          :items='genders'
                          item-text='name'
                          return-object
                        >
                        </v-select>
                      </v-col>
                    </v-row>
                  </v-form>
                </v-container>
              </v-card-text>

              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" rounded @click="close">Cancel</v-btn>
                <v-btn color="primary" rounded @click="save">Save</v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-toolbar>
      </template>
      <template v-slot:item.action="{ item }">
        <v-icon
          small
          color="green"
          class="mr-2"
          @click="editItem(item)"
        >
          mdi-pencil
        </v-icon>
        <v-icon
          small
          color="red"
          @click="deleteItem(item)"
        >
          mdi-delete
        </v-icon>

      </template>
      <template v-slot:no-data>
        <v-btn color="primary" @click="initialize">Reset</v-btn>
      </template>
    </v-data-table>
</template>

<script>
import axios from 'axios'
import Client from '../../services/clients';
import Gender from '../../services/genders';

  export default {
    data: () => ({
      dialog: false,
      headers: [
        {
          text: 'First Name',
          align: 'start',
          sortable: false,
          value: 'firstName',
        },
        { text: 'Last Name', value: 'lastName' },
        { text: 'Email', value: 'email' },
        { text: 'Phone', value: 'phone' },
        { text: 'Mobile Phone', value: 'mobilePhone' },
        { text: 'Gender', value: 'gender.name' },
        { text: 'Actions', value: 'action', sortable: false },
      ],
      clients: [],
      genders: [],
      errors: [],
      editedIndex: -1,
      editedItem: {
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        mobilePhone: '',
        gender: '',
      },
      defaultItem: {
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        mobilePhone: '',
        gender: '',
      },
    }),
    computed: {
      formTitle () {
        return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
      },
    },
    watch: {
      dialog (val) {
        val || this.close()
      },
    },
    created () {
      this.initialize()
    },
    methods: {
      initialize () {
        Client.list().then(response => {
          this.clients = response.data
        }).catch(e => {
          console.log(e)
        });
        Gender.list().then(response => {
          this.genders = response.data
        }).catch(e => {
          console.log(e)
        });

      },
      editItem (item) {
        this.editedIndex = this.clients.indexOf(item)
        this.editedItem = Object.assign({}, item)
        this.editedID = this.editedItem.id
        this.dialog = true
        axios.put('http://192.168.26.130:3000/client/' + item.id)
          .then(response => {
            this.response = response
        }).catch(error => {
          console.log(error.response)
        });
      },

      deleteItem (item) {
        if (confirm("Do you really want to delete?")) {
          const index = this.clients.indexOf(item)
            this.deletedItem = Object.assign({}, item)
            this.deletedID = this.deletedItem.id
            this.clients.splice(index, 1);
          axios.delete('http://192.168.26.130:3000/client/' + item.id)
            .then(response => {
              this.response = response
            }).catch(error => {
                console.log(error.response)
              });
        }
      },

      close () {
        this.dialog = false
        setTimeout(() => {
          this.editedItem = Object.assign({}, this.defaultItem)
          this.editedIndex = -1
        }, 300)
      },

      save () {
        if (this.editedIndex > -1) {
          Object.assign(this.clients[this.editedIndex], this.editedItem)
        } else {
            this.clients.push(this.editedItem)
            axios.post('http://192.168.26.130:3000/client/', this.editedItem)
              .then(response => {
                console.log(response)
              }).catch(error => {
              console.log(error.response)
            });

        }
        this.close()
      },

    },
  }
</script>

Фрагмент кода, который сохраняется в базе данных:

this.clients.push(this.editedItem)
  axios.post('http://192.168.26.130:3000/client/', this.editedItem)
 .then(response => {
  console.log(response)
}).catch(error => {
console.log(error.response)

Может ли кто-нибудь спасти меня? Заранее большое спасибо.

...