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.
2
Answers
In Vue.js, you should use v-model for two-way data binding. The v-model directive is a convenient shorthand for binding data to form inputs and updating the data on user input. However, it can’t be directly used as a prop or passed as a parameter. Instead, you can pass the entire object and use it in the method.
Here’s how you can modify your code:
In this example, each item in the data array is an object with an id and value property. The v-model directive is bound to item.value. When you click the button, the submitTest function is called with the entire item object, and you can access the value property from there.
Make sure to use ref to create a reactive reference to your data array in the setup script.
Note: The :key="idx" is added to the to provide a unique key for each item in the loop. This helps Vue.js efficiently update and re-render components when the array changes.
Without changing your data – this works