2017-08-30 42 views
1

我不明白是什麼......希望這個VUE! 如果可以的話請幫忙! 這是我在currentFullData例如代碼在一個陣列中的Vue JS變化的數據變化

var groupadding = new Vue({ 
el: '#groupAdd', 
data:{ 
    currentFullData: [], 
    localData: [] 
    }, 
    methods: { 
    getDepartment() { 
     var sendData = id; // this is example 
     this.$http.post('some api ', sendData, {emulateJSON: true}) 
     .then(resp => { 
     this.currentFullData = resp.data;  
     } 
    }, 
    getLocalDepartment() { 
    this.localData = this.currentFullData; 
    } 
    } 
}) 

我有4個布爾字段,「創建」,「讀」,「更新」,「刪除」

這4個領域得到localData過,但是當我在localData中改變了他們中的一些,他們在currentFullData中也改變了!!!!!!!!!!!!!!!

soooooo任何人都可以解釋我跆拳道是這個?!?!?!

回答

1

這是因爲你實際上是修改同一對象(如你寫this.localData = this.currentFullData;

如果你想使用this.localData向currentFullData初始化,你需要複製:

this.localData = Object.assign({}, this.currentFullData);

看到https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

+0

NOP,同樣的結果... :( – Jorjini

+0

哦NVM,我沒看出來是一個數組而不是對象,請參閱anchal20克隆和數組的答案。 – reinarg

+0

對不起,我的回答是,你是對的 this.currentFullData = cloneArray(this.currentFullData,data); function cloneArray($ name,$ array) {name} = JSON.parse(JSON.stringify($ array)); } 這WOOOOOOOOOOOOOOOOOORKS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 謝謝你!!!! – Jorjini

1

謝謝你的問題。問題不在於vue和數據值'currentFullData'和'localData'。當你的數據變量是數組,因此當你分配這樣this.localData = this.currentFullData然後this.localData值是一個指向this.currentFullData。所以,當你改變localData時,currentFullData也會改變。 因此,爲了避免這種情況,合格this.currentFullData參考,this.localData這樣this.localData = this.currentFullData.slice()

更多的瞭解,你可以參考this question about arrays on stackoverflow

+0

未捕獲的(以諾)類型錯誤:this.currentFullData.slice不是一個函數 – Jorjini

+0

你可以檢查我的codepen https://codepen.io/anchal20/pen/QMzQQG,也是我的鏈接上面的共享。我希望你輸入正確,它應該是this.currentFullData.slice()和resp.data應該是數組類型。 – anchal20