Home > database >  Transfer item data to editing window for multiple items
Transfer item data to editing window for multiple items

Time:11-27

I have list of elements that I am looping with and it contains text.

<div v-for="item in items" :key="item.id">
    <p>{{ item.description }}</p>
    <button @click="edit=true">Edit</button>
    <textarea v-if="edit" v-model=editItem />
</div>

How can I transfer item description to text area each time I click to edit?

I could do it this way:

function somefunction(item) {
    edit.value = true
    editItem.value = item.description
}

but the thing is, it will allow to only edit one item at a time, I want to be able to have enabled multiple of editing windows. Can someone give me advice how to do it?

CodePudding user response:

To edit multiple rows inside a v-for, here you are an approach that I've used over all view/model frameworks:

  • Create an array where you push all ids/indexes of rows to edit.
  • For v-model of each item, you can use a reactive object where you set the values using ids/indexes as key.

DEMO: https://jsfiddle.net/The_Bear/0hvtxb3r/47/

TEMPLATE

<div v-for="item in items" :key="item.id">
    <p>{{ item.description }}</p>
    <button @click="setEdit(item.id)">Edit</button>
    <textarea 
        v-if="isEdit(item.id)" 
        :value="editItem[item.id]" 
        @input="updateEditItem(item.id, $event.target.value)"
    />
</div>

JS

{
  //...
  data: {
    editableRows: [],
    editItem: {},
    items: [
      { id: 1, description : "Learn JavaScript" },
      //...
    ]
  },
  methods: {
    isEdit(id) {
        return this.editableRows.indexOf(id) >= 0;
    },
    setEdit(item){
        this.editableRows.push(item.id);
        this.updateEditItem(item.id, item.text);
    },
    updateEditItem(key, value) {
        this.editItem= {
            ...this.editItem,
            [key]: value
        };
    }
  }
}
  • Related