Search code examples
vue.jsvuejs3vue-component

How to handle list of forms in Vue JS


I have a list of forms and I want to bind them with a single ref.

The ref will hold an object with form number as keys and values should be again an object whose keys are be bound to the nested object keys.

const forms = reactive({})

// template 

<form v-for="item in list" :set="forms[item.id]={}">
  <input v-model="forms[item.id]['name']" />
  <input v-model="forms[item.id]['email']" />
  <input v-model="forms[item.id]['phone']" />
</form>

I have the above implementation but field refs don't seem to work, I can't either enter values in the fields.

A working demo

I want to be able to handle nested objects as refs to input


Solution

  • You must initialize the ref first, shortcut initializations like v-const have only recently been introduced into the plan

    
    
    const list = ref( [1,2,3] )
    
    watch(list, list => {
      list.forEach(item => form.value[item] = {})
    }, { immediate: true })