0

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': '',
            }
          });
        }
      },
    },
  });
Lauren Mastroni
  • 113
  • 1
  • 9

1 Answers1

1

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]">
Jacob Goh
  • 19,800
  • 5
  • 53
  • 73
  • 1
    Thanks...I think this is close but now I'm getting the following error: Error in render: "TypeError: Cannot read property 'date-0' of undefined" How to solve this? Thanks in advance! – Lauren Mastroni Mar 29 '18 at 05:42
  • @LaurenMastroni I think the reason is that `newFields` is an empty array. `newFields[0]` doesn't exist. Perhaps you can try to set the initial value of `newFields` to `[ {} ]` (an array with only 1 value, which is an empty object), so that `newFields[0]` won't be undefined anymore. I am not sure why you design your data this way though. Hope that this won't affect your app logic. – Jacob Goh Mar 29 '18 at 05:48
  • I'm not sure why either haha...thanks for your help! – Lauren Mastroni Mar 29 '18 at 05:57