[英]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.我是 Vue.js 的新手(我主要使用 PHP),我正在尝试创建简单的视图,用户可以在其中从一个组件添加 object 并将其副本放置到另一个组件中。
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.据我所知,object“任务”是通过引用传递的,当我尝试创建一个空的 object 或数组并将“任务”插入到新创建的对象/数组中时,当我更改原始“任务”时,它也是在新的 object 内部进行了更改,我不希望那样。
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.我正在从我创建的 API 获取我的数据(任务),并且我正在使用分页系统,因此我希望能够切换页面而不会从固定页面丢失它。
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?任何人都可以确认或拒绝这一点吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.