2017-10-04 53 views
0

我有一個奇怪的js/vuejs問題,當一個變量在函數內部更新(從data(){})中獲取數據時,數據也會隨之更新。如何從更新數據變量停止vuejs方法變量

這是一個代碼示例。它檢查如果用戶沒有輪廓的圖像,它會通過愛可信的形象名稱發送到一個API,如果用戶已經映像,它可以將當前圖像添加到列表,並將其發送到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 => {}) 
}, 

這裏的問題是this.person.images得到更新,即使我只是想用它來獲取當前的圖像列表。

如果在執行att.push(file.name)時檢查if/else塊,this.person.images;也會更新。我僅使用att來存儲當前的圖像列表並將其發送給api。

無論如何只能使用this.person.image來獲取信息?

我可以使用const att = this.person.image,但之後我無法更新att

回答

1

更簡單的解決方案將是

var images=JSON.parse(JSON.stringify(this.person.images)) 

避免發生循環。

1

因爲在Javascript中當你這樣做:

var images = this.person.images; 

圖像的值現在是 「this.person.images」 的參考。解決這一問題

一種想法是循環通過「影像」陣列的每個項,並將其添加到「ATT」陣列像這樣:

for (var i = 0,len = images.length; i < len; i++) { 
      att.push(images[i]); 
     } 

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 => {}) 
}, 

基本上與替換att = images

+0

我很驚訝這是它的唯一解決方案。我曾想過這樣做,但我認爲可能有更好的方法。在那兒? – hidar

+0

看看這個數組函數在Javascript中,它可能是你的問題的解決方案。 https://www.w3schools.com/jsref/jsref_copywithin.asp – Tarek

+0

var images = JSON.parse(JSON.stringify(this.person.images))。使用這個簡單的解決方案 –