简体   繁体   中英

Vue: Collect all (or some) form values simultaneously

I'm trying to understand if I can achieve with vue.js the same handy process I use to follow with vanilla/jquery to collect simultaneously all (or only some of) the form fields I need.

When dealing with forms usually I never submit them the old school way, instead, I add a class my-update to the form fields I want to send and then I loop them this way:

let objectToUpdate = {};
      $(".my-update").each(function(index, element) {
        objectToUpdate[$(this).data("db-field")] = $(this).val();
      });

Then I just pass the object to an Ajax POST call and send it to the backend API. With Vue, it's way simple to get data since we have the property (usually called data ) already available within the Vue instance but the problem is if I just send the this.$data it will catch not only the properties (all of them without choice) but also all methods included in the object (getter/setter, ...).

Do you have any best practice or suggestions to share to achieve the same I usually do with a couple of lines of jquery but in Vue?

Usually in Vue form controls are binded to data via v-model . Let's say my Vue instance/component is like:

new Vue({
  data: {
    user: {
      name: '',
      surname: '',
      phone: '',
    }
  },
  methods: {
    send() {
      // send this.user through http
    }
  }
});

And my template is like:

<form @submit="send">
<input name="username" v-model="user.name" />
<input name="surname" v-model="user.surname" />
<input name="phone" v-model="user.phone" />
<button> send </button>
</form>

In such scenario, you have all the user information in your component/instance via this.user . You don't need to send this.$data at all if you create an object to manage your form fields (like this.user in this example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM