Search code examples
formsvue.jssubmitelement-ui

Vue2 how to only submit form values?


I have a form page and I use it for both create and update

My form fields are like this;

enter image description here

content: (...)
i18n: (...)
image: (...)
name: (...)
orderIndex: (...)
position: (...)

I can successfully submit a request.

When we come to the update process, I get the data in this way and sync it. I'm getting extra data (this.myForm = response.data)

When I send an update request I just want the form fields to go but it goes like this

I don't want to send createdAt, deleted, updatedAt, _id fields

enter image description here

content: (...)
createdAt: (...)
deleted: (...)
i18n: (...)
image: (...)
isEnabled: (...)
name: (...)
orderIndex: (...)
position: (...)
updatedAt: (...)
_id: (...)

How can I submit only form fields? (I am using element-ui btw)

Is there something like this.$refs.myForm.fields or this.$refs.myForm.values I couldn't find it

For example Angular reactive form has something like this --> this.testimonialForm.patchValue(response.data);

  data() {
    return {
      id: null,
      testimonialForm: {
        name: '',
        position: '',
        content: '',
        orderIndex: '',
        i18n: '',
        image: {
          path: ''
        }
      }
    }
  },
  computed: {
    ...mapState({
      testimonialData: state => state.testimonial.testimonial
    })
  },
  created() {
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      this.fnGetTestimonialInfo(this.id)
    }
  },
  methods: {
    fnCreateTestimonial() {
      this.$store.dispatch('testimonial/create', this.testimonialForm).then(() => {
        this.$router.push('/testimonial/list')
      })
    },
    fnUpdateTestimonial() {
      const data = { id: this.id, data: this.testimonialForm }
      this.$store.dispatch('testimonial/update', data).then(() => {
        this.$router.push('/testimonial/list')
      })
    },
    fnGetTestimonialInfo(id) {
      this.$store.dispatch('testimonial/get', id).then(() => {
        this.testimonialForm = this.testimonialData
      })
    },
  }

Solution

  • Solved like this :

    const pick = require('lodash/pick')
    const formKeys = Object.keys(this.testimonialForm)
    this.testimonialForm = pick(this.testimonialData, formKeys)
    

    Thanks to @gguney for the guidance.