1

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?

1
  • I don't think there's a "vue way" to do what you are doing here. Commented Jan 25, 2021 at 16:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

So in my case it's enough if the structure looks like this: ``` tasks: id, name, prop1, prop2, prop3 ``` ?
ya if your attrs like name,prop1, prop2 etc are not objects but just direct values like integer or strings
That is correct they are "simple" variables types. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.