简体   繁体   中英

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

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': '',
            }
          });
        }
      },
    },
  });

You can save the name as a reactive data. For eg, 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]">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM