V
V
Vitaly B2020-08-12 18:29:01
Vue.js
Vitaly B, 2020-08-12 18:29:01

Form on vue. How right?

I'm considering an example of submitting a form to the server.
In this example, the confusing parts are:

data() {
    return {
      name: '',
      email: '',
      caps: '',
      response: '',
      activeClass: 'active'
    }

And
name: this.name,
        email: this.email,
        caps: this.caps


Are there options to reduce the amount of code?
How to correctly declare an array/object in data, in which, on submit/click, place an object with the data of the form fields of the form {key: value}?
Serialization in vue possible?

In general, vue can help reduce the amount of code, or will it give a clearer orientation in the code?
I am writing a project in which there is a lot of data, a lot of tables, forms and various dynamic elements. Started with jQuery, gradually moving to pure js. But it is already difficult to navigate the code. I wish it was easier to write. And if not less code, then at least to simplify the logic of the project. And then with experiments on solving the same problems in different ways, I myself get confused in the final code.

<div id="app">
  <form @submit.prevent="submitForm">
    <div>
      <label for="name">Name:</label><br>
      <input id="name" type="text" v-model="name" required/>
    </div>
    <div>
      <label for="email">Email:</label><br>
      <input id="email" type="email" v-model="email" required/>
    </div>
    <div>
      <label for="caps">HOW DO I TURN OFF CAPS LOCK:</label><br>
      <textarea id="caps" v-model="caps" required></textarea>
    </div>
    <button :class="[name ? activeClass : '']" type="submit">Submit</button>
    <div>
      <h3>Response from server:</h3>
      <pre>{{ response }}</pre>
    </div>
  </form>
</div>


new Vue({
  el: '#app',
  data() {
    return {
      name: '',
      email: '',
      caps: '',
      response: '',
      activeClass: 'active'
    }
  },
  methods: {
    submitForm() {
      axios.post('//jsonplaceholder.typicode.com/posts', {
        name: this.name,
        email: this.email,
        caps: this.caps
      }).then(response => {
        this.response = JSON.stringify(response, null, 2)
      })
    }
  }
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-08-12
@vitaliy_balahnin

data() {
    return {
      formData: {
        name: '',
        email: '',
        caps: ''
      },
      response: '',
      activeClass: 'active'
    }
  },

submitForm() {
   axios.post('//jsonplaceholder.typicode.com/posts', this.formData)
}
And, accordingly, v-model="formData.name" and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question