skip to Main Content

I want to assign different and unique parameter in loop to each input tag (v-model)

I tried the code below

<template>
<div v-for="item in lst" key="item">
 <input :v-model="item"> </input>
</div>
</template>
<script setup>
var lst = ['first_vmodel_value','second_vmodel_value']

</script>

By doing this I want to access to each input tag v-model value. The example above, there are only two item value but actually much more value exists.

  • The code above is not working. I want to assign unique v-model value to each input tag.
    The intent of the code is to access v-model value using lst item, for example first_vmodel_value or second_vmodel_value

2

Answers


  1. use ref/reactive Object – and it’s v-model not :v-model

    The content of your lst would be used to create properties in models (it’s an arbitrary name)

    <script setup>
    import {reactive} from "vue";
    var lst = ['first_vmodel_value','second_vmodel_value']
    const models = reactive({});
    </script>
    
    <template>
      <div v-for="item in lst" key="item">
        <input v-model="models[item]"/>
      </div>
    </template>
    

    Or possibly it’s better like this

    <script setup>
    import {reactive} from "vue";
    const models = reactive({
      first_vmodel_value: '',
      second_vmodel_value: '',
    });
    </script>
    
    <template>
      <div v-for="item in models" key="item">
        <input v-model="item"/>
      </div>
    </template>
    
    Login or Signup to reply.
  2. You can create an array of refs.

    <template>
    <div v-for="item in lst">
     <input v-model="item.value">
    </div>
    </template>
    <script setup>
    import { ref } from 'vue';
    const lst = ['first_vmodel_value','second_vmodel_value'].map(k => ref(k));
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search