简体   繁体   中英

@input to enter new items only on click of a button

I have an array of objects and I used v-for to display them. However I want to change few of those items from the array and save only the changed objects in a new object. I've mapped over items in the justAnotherSaveFunction but it saves all the items from the array and not just the changed items therefore I used @input in the <b-form-input> . But due to this, an object is pushed to the array with every keystroke. How do I make it push to the array only when I click the save button?

template

<b-card-group columns>
  <b-card v-for="item in items" :key="item.id" no-body>
    <b-card-header>
      Item {{ item.id }}
    </b-card-header>
    <b-card-body>
      <b-form-group v-for="(value, index) in anotherItems.values" :key="index" class="form-group">
        <span>{{ val }}</span>
        <p>{{ item[val] }}</p>
        <b-form-input v-model="item[value + '_change']" class="form-control" @input="(newValue) => addChangedValue(newValue, item.id)"></b-form-input> //want to keep only the
        changed items from here in the newData const
      </b-form-group>
    </b-card-body>
  </b-card>
</b-card-group>
<b-button variant="primary" @click="justAnotherSaveFunction">
   Save
</b-button>

Methods:

data(){
   return{
     item: [
         {
       id: 1
       key: "something"
       val: "somethng"
       val_change: "somethhing"
 },{id: 3
       key: "something2"
       val: "something2"
       val_local: "something2"
 },
],
anotherItems: {
    {
     "name":"Randome name",
     "values":["val"],
   }
  },
  changedValueArray: []
},
methods: {
      addChangedValue(newValue, itemId) {
        this.changedValueArray.push({ id: itemId, value: newValue})
      },
  justAnotherSaveFunction() {
    console.log("objects\n" +JSON.stringify(this.changedValueArray)) //I saw many objects for the same item id here because with every input, a new object was pushed to the array
    const newData = this.items.map((item) => {
      const newItem = {};
      newItem.item_id = item.id;

      this.anotherItems.values.forEach((val) => {
        newItem[val] = item[`${val}_change`];
      });
      return newItem;
    });
  }
}

将每次输入值更改时触发的@input替换为@change ,后者仅在您离开输入时触发(模糊)

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