Home > other >  How to make a clone of the array object with new id and same name?
How to make a clone of the array object with new id and same name?

Time:06-23

I'm new at vue3 and javascript. I have 2 lists and drag and drop system. The problem is when I drag and drop component from one list to another, I increase an id by 1, but I can't get the name of dragged object and display it. The problem displayed at methods in method "cloneComponent"

<template>
  <div >
    <div >
      <h3>Компоненты бота:</h3>
      <draggable
          
          :list="list1"
          :group="{ name: 'people', pull: 'clone', put: false }"
          :clone="cloneComponent"
          @change="log"
          item-key="id"
      >
        <template #item="{element}">
          <div >
            {{ element.name }}
          </div>
        </template>
      </draggable>
    </div>

    <div >
      <h3>Конструктор</h3>
      <draggable
          
          :list="list2"
          group="people"
          @change="log"
          item-key="id"
      >
        <template #item="{ element, index }">
          <div >
            {{ element.name }}
            <div>
              <input type="text"  v-model="element.text" placeholder="Введите текст компонента" />
              <span @click="remove(index)" >x</span>
            </div>
          </div>
        </template>
      </draggable>
    </div>

    <div>
      <button >Сгенерировать бота</button>
    </div>
    <rawDisplayer  :value="list1" title="List 1" />
    <rawDisplayer  :value="list2" title="List 2" />
  </div>
</template>

<script>
import draggable from "vuedraggable";
let idGlobal = 4;
export default {
  name: "clone",
  display: "Clone",
  order: 2,
  components: {
    draggable
  },
  data() {
    return {
      list1: [
        { name: "Сообщение", text: "", id: 1 },
        { name: "Заметка", text: "", id: 2 },
        { name: "Кнопка", text: "", id: 3 },

      ],
      list2: []
    };
  },
  methods: {
    log: function(evt) {
      window.console.log(evt);
    },
    cloneComponent() {
      return {
        id: idGlobal   ,
      }
    },
    remove(idx) {
      this.list2.splice(idx, 1);
    },

  }
};
</script>

How to return not only "id", but "name" at the same time? Please help.

CodePudding user response:

You need to send the item to the other list

// tolist = can be 1 or 2
cloneComponent(item, tolist) {
    if (tolist === 2) {
        this.list2.push(item)
    } else {
        this.list1.push(item)
    }
}
  • Related