fencepencil
fencepencil

Reputation: 407

VueJS: Dynamic v-model inside v-for

Trying to update an input field containing a v-model dynamically, based on the v-for array I've setup:

<div v-for="input in inputs" :key="input.id">
    <h6>{{ input.name }}</h6>
    <input v-model="input.vmodel" />
</div>
export default {
    setup() {
        const customerName = 'customer Name';
        const hostName = 'host Name';

        const inputs = [
            { id: 1, name: 'Customer Name', vmodel: customerName },
            { id: 2, name: 'Router Hostname', vmodel: hostName }
        ];

        return {
            inputs,
            customerName,
            hostName
        };
    }
}

The text shows up in the input field but it's not dynamic when trying to type something else, it's not binding.

<template>
    <pre>
      <code>
  customer name {{ customerName }}
  hostname {{ hostName }}
      </code>
    </pre>
</template>

Upvotes: 0

Views: 508

Answers (1)

beingyogi
beingyogi

Reputation: 1416

You can make use of computed properties

export default {
  data() {
    return {
      inputs: [
        { id: 1, name: "Customer Name", vmodel: "customer Name" },
        { id: 2, name: "Router Hostname", vmodel: "host Name" }
      ]
    };
  },
  computed: {
    customerName() {
      return this.inputs[0].vmodel;
    },
    hostName() {
      return this.inputs[1].vmodel;
    }
  }
};

Upvotes: 1

Related Questions