Search code examples
javascripthtmlvue.js

How to access v-model value using parameter in VUE


I want to access v-model value using parameter and I try the code below

<template>
 <div v-for="(item, idx) in data">
   <input :id="item" :v-model="item"></input>
   <button @click="submitTest(item)"> testbtn </button>
 </div>
</template>

<script setup>
var data = {'test1': 'val1', 'test2': 'val2'}
function submitTest(itemParam){
 alert(itemParam.value)
}
</script>

And actually in submitTest function(alert line), it doesn't access to input tag v-model but itemParam(string value itself) value. What I want is to access input 'item value' using parameter that is delivered by item parameter.

I tried the code above and as a result, it actually access to 'itemParam' string value itself not delivered parameter.


Solution

  • Without changing your data - this works

    NOTE: you can also use reactive instead of ref

    <script setup>
    import { ref } from 'vue'
    const data = ref({'test1': 'val1', 'test2': 'val2'})
    function submitTest(key){
     alert(key)
    }
    </script>
    
    <template>
    <div v-for="(value, key) in data" :key>
       <input :id="key" v-model="data[key]"/>
       <button @click="submitTest(value)"> testbtn </button>
     </div>
    </template>