Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65888755/proper-way-of-object-copy-from-one-element-to-another-in-vue-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...