[Vuejs]-Vue.js 2, do I have to use multiple v-models for to bind values to a form component?

0👍

You can follow the below approach to create a reactive model.

<template>
  <input
    type="text"
    placeholder="Firstname"
    v-model="reactiveValue.firstName"
  />
  <!-- Your form code -->
</template>
<script>
export default {
  name: "App",
  components: {},
  props: {
    value: {
      type: Object,
      default: () => ({
        firstName: "",
        lastName: "",
        email: "",
        phone: "",
      }),
    },
  },
  data() {
    return {};
  },
  computed: {
    reactiveValue: {
      get() {
        return this.value;
      },
      set(value) {
        console.log(value);
        this.$emit("input", value);
      },
    },
  },
};
</script>

Then call it like:

 <myForm v-model="user" />

It uses computed properties to create reactive data.

Leave a comment