为什么我将原始Vuex对象的值分配给局部变量并操纵该局部值时会被更改?如有必要,我可以发布store.js。
我有这样的东西:
data() {
return {
localObject: [],
};
},
computed: mapState(["storeObject"]), // main store object
created() {
this.localObject = this.storeObject;
this.prepareData();
},
methods: {
prepareData() {
this.localObject.forEach((event, i) => {
delete event.artist_supporting;
delete event.genre;
});
// console.log(this.storeObject); // why is this object getting changed by the localObject.forEach?
}
}
这是完整的compute()块。如果我在计算值this.eventsData
的顶部控制台calendarData()
,则它已按预期完成。但是,如果我在返回前在底部操纵this.eventsData
,就好像我直接操纵它一样。
computed: {
...mapState(["loading", "eventsData"]),
calendarData() {
console.log(this.eventsData); // correct "complete" object
let data = this.eventsData;
data.forEach((event, i) => {
delete event.artist_supporting;
delete event.genre;
delete event.venue;
delete event.venue_city;
delete event.venue_state;
delete event.capacity;
delete event.announce_date;
delete event.onsale_date;
delete event.promoter;
delete event.business_unit;
delete event.show_type;
delete event.confirm_date;
delete event.cancelled_date;
delete event.status;
event.venue_id = `event_${i}`;
event.id = event.venue_id;
event.title = event.artist_headliner;
event.startDate = event.event_date;
delete event.venue_id;
delete event.artist_headliner;
delete event.event_date;
let date = new Date(event.startDate);
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
event.startDate = year + "-" + month + "-" + day;
});
console.log(this.eventsData); // edited object
return data;
},
},
答案 0 :(得分:1)
因为这样做this.localObject = this.storeObject;
,所以您将storeObject
的引用分配给localObject
,这使得两个变量都指向相同的内存。突变其中任何一个都会影响另一个。如果需要隔离效果,则必须进行深层复制。最简单的方法是使用JSON.parse(JSON.stringify(...)
:
this.localObject = JSON.parse(JSON.stringify(this.storeObject))
答案 1 :(得分:0)