0


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.

  • This seems as bad approach. Of course you can use `v-model` on your child component - just bind `v-model` on your inputs into a custom computed with getter returning the prop value and setter emiting the `update:xxx` event... – Michal Levý Nov 23 '21 at 11:07
  • Can you post `addAsset` method here. Also, try avoiding using `index` as key for lists where the length of the array is going to change. If you're only adding elements to the array, that's fine. But if you intend to add a `removeAsset` button/method, you should by all means avoid using `index` as key. – saibbyweb Nov 24 '21 at 16:09

0 Answers0