Aftermathx25
Aftermathx25

Reputation: 11

Proper way of object copy from one element to another in Vue.js

I am new to Vue.js (I mostly use PHP) and I am trying to creating simple view where user can add an object from one component and place it's copy into another component.

Main template

<template>
   <div class="left">
      <TaskList :tasks="tasks" v-on:pinned-add-task="pinnedAddTask" />
   </div>
   <div class="right">
      <PinnedList :pinned="pinned" />
   </div>
</template>

TaskList

<template>
  <div class="task-list">
      <div v-for="task in tasks" :key="task.id">
          <TaskItem :task="task" v-on:pinned-add-task="$emit('pinned-add-task', task)" />
      </div>
  </div>
</template>

TaskItem

<template>
   <div>
     <p>{{task.name}}</p>
     <button v-on:click="$emit('pinned-add-task', task)">+</button>
   </div>
</template>

And as far as I am aware object "task" is passed by reference and when I try to create an empty object or an array and insert "task" into that newly created object/array when I change original "task" it is also being changed inside that new object and I don't want that.

I am getting my data (tasks) from API that I have created and I am using pagination system so I want to be able to switch pages without losing it from the pinned page.

I created code which looks like this but I don't like it and I don't think that's a good way to do this:

    pinnedAddTask(item) {
      let pQuantity = 1; // I use this value because I want to be able to pin one task multipletimes
      let left = this.pinned;
      let right = [];
      for (let task of this.pinned) {
        if(item.id == task.id) {
          pQuantity = task.quantity + 1;
          left =  this.pinned.filter(eItem => eItem.id < item.id);
          right =  this.pinned.filter(eItem => eItem.id > item.id);
        }
      }
      const clone = {...item, quantity: pQuantity};

      this.pinned = [...left, clone, ...right];
    }

Can anyone confirm or reject this?

Upvotes: 1

Views: 906

Answers (1)

Amaarockz
Amaarockz

Reputation: 4684

Yes this one is fine if thats just a shallow copy [ level-one object]. But if you are having a nested object then you might have to use recursive methodology or use any external libary like lodash

Upvotes: 1

Related Questions