Home > Software engineering >  v-for with model vuejs
v-for with model vuejs

Time:11-25

I need to execute a v-for, however I do not know how to add a v-model for each different component inside of v-for;

<template>
<ProfilePasswordField
      v-for="(item, index) in profilePasswordItems" 
      :key="index"
      :profilePasswordItem="item"
      v-model="???"
>
</template>

This v-for will always be three items and I want to name the v-model's as: ['passaword', 'newPassword', confirmNewPassword']

How can I add those names dinamically for the v-model inside v-for?

I tried to do a list inside data() but it did not work. Something like that:

data (){
        return{
            listPassword: ['passaword', 'newPassword', 'confirmNewPassword']
        }
},
methods: {
        method1 () {
            console.log(this.passaword)
            console.log(this.newPassword)
            console.log(this.confirmNewPassword)
       }
}

CodePudding user response:

The v-model directives cannot update the iteration variable itself therefore we should not use a linear array item in for-loop as the v-model variable.

There is another method you can try like this-

In the parent component-

<template>
  <div>
    <ProfilePasswordField
      v-for="(item, index) in listPassword" 
      :key="index"
      :profilePasswordItem="item"
      v-model="item.model"
    />
    <button @click="method1()">Click to see changes</button>
 </div>
</template>
    
<script>
  export default {
  name: "SomeParentComponent",

  data() {
    return {
      listPassword: [
        { model: "passaword" },
        { model: "newPassword" },
        { model: "confirmNewPassword" },
      ],
     };
   },
    
   methods: {
     method1() {
       this.listPassword.forEach((item) => {
         console.log(item.model);
       });
     },
   },
  }
 </script>

And in your ProfilePasswordField you can emit the input event to listen to the respected changes in v-model binding. For example, the ProfilePasswordField component could be like this-

<template>
  <v-text-field :value="value" @input="$emit('input', $event)"/>
</template>

<script>
 export default {
   name: "ProfilePasswordField",

   props: {
    value: {
     required: true 
    } 
 }
</script>

In the parent component's console, you should see the changes made by the child component.

  • Related