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]">