I have a strange js/vuejs problem that when a variable is updated inside a function (getting data from data(){}), it goes up the data also updates it.
Here is a code example. It checks if user has no profile image, it will send the image name to an api via axios, if user has already images then it will append the current image to the list and send it to the api:
addImage (file) {
var URL = 'http://foo.com/api';
var images = this.person.images;
let att = []
if(images.length) {
att = images
att.push(file.name)
}else{
att.push(file.name)
}
axios.post(URL, {
attachements: att
}).then(
// update dom
).catch(err => {})
},
The problem here is that this.person.images
gets updated, even though I just want to use it to get the current list of images.
If you check the if/else block when att.push(file.name)
is executed the this.person.images;
also gets updated. I am using the att
only to store the current list of images and send it to api.
Is there anyway to use this.person.image
to get the information only?
I could use const att = this.person.image
but then I would not be able to update att
afterwards.
Because in Javascript when you do :
var images = this.person.images;
The value of images is now a reference for "this.person.images".
One idea to solve that problem is to loop through each item of "Images" Array and add it to the "att" array like so :
addImage (file) {
var URL = 'http://foo.com/api';
var images = this.person.images;
let att = []
if(images.length) {
for (var i = 0,len = images.length; i < len; i++) {
att.push(images[i]);
}
att.push(file.name)
}else{
att.push(file.name)
}
axios.post(URL, {
attachements: att
}).then(
// update dom
).catch(err => {})
},
Basically replace att = images
with :
for (var i = 0,len = images.length; i < len; i++) {
att.push(images[i]);
}
More simple solution would be
var images=JSON.parse(JSON.stringify(this.person.images))
avoid looping.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.