Vue.js How to target object with unknown name in an array on v-model input Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Vue.js How to target object with unknown name in an array on v-model input without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am generating an object onclick with an automatically-generated name. The name will be different each time. I then want to change the object’s values with an input using v-model. How can I target the object if the name is unknown? Here’s what I have so far:

<ul>
  <li v-for="type in types" @click="addNew(type)">{{ type }}</li>
</ul>

<form v-if="Object.keys(newFields).length !== 0">

  <input type="text" v-model="newFields[0].?????????">

</form>

  <script>
  new Vue ({
    el: '#app',
    data: {
      types: [
        'date',
        'number',
        'currency',
        'text',
      ],
      savedFields: [

      ],
      newFields: [

      ]
    },
    methods: {
      addNew: function (type) {

        const name = `${type}-${Object.keys(this.savedFields).map(key => key === type).length}`;

        if (Object.keys(this.newFields).length == 0) {
          this.newFields = Object.assign({}, this.newFields, {
            [name]: {
              'type': type,
              'displayLabel': '',
              'defaultValue': '',
            }
          });
        }
      },
    },
  });

Answer

You can save the name as a reactive data. For e.g., save it in currentName

<script>
    new Vue({
        el: "#app",
        data: {
            //...
            currentName: null
        },
        methods: {
            addNew: function (type) {
                const name = ""; //...

                this.currentName = name;

                //...
            }
        }
    });

</script>

and for the v-model,

<input type="text" v-model="newFields[0][currentName]">
We are here to answer your question about Vue.js How to target object with unknown name in an array on v-model input - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji