I've been struggling a wile with this and would apreaciate some assistance.
I have a Vue3 child component that contains two input fields.
Child
<template>
<label>
<span>asset value</span>
<input type="number" :value="value" />
</label>
<label>
<span>target percentage</span>
<input type="number" :value="targetPercentage" />
</label>
</template>
There is a button in my main component to add this component unlimited times to the template.
I am trining to use the Composition API to get the values from those input fields via ref.
Parent
setup() {
// List of predefined assets
const assetList = reactive([
{
title: 'Position 1',
value: '',
targetPercentage: '',
}
]);
const assetsRefs = ref([]);
// Make sure to reset the refs before each update.
onBeforeUpdate (() => {
assetsRefs.value = [];
})
onUpdated (() => {
console.log(assetsRefs)
})
return {
assetList,
assetsRefs,
};
}
In the template of my main component I render those assets like the following
Parent
<template>
<div>
<Asset v-for="(asset, index) in assetList"
:key="index"
:value="asset.value"
:targetPercentage="asset.targetPercentage"
:ref="element => { assetsRefs[index] = element }"
/>
<button @click="addAsset">Add New Position</button>
<button @click="onSubmit">Calculate</button>
</div>
</template>
What I am trying to achive is, that there is some sort of two way binding between the parent and the child components. I obviously can't use v-model in my child components, because I already use props to bind the predefined values from the assetList (first code block).
I already found good examples for todo lists with refs and v-for or for submitting forms so that I could render multiple assets. But I never got some input field rendering with v-for and refs to actually get the input values.