2017-03-16 42 views
0

我有這樣的代碼 -無法更新 「數據」 使用 「計算」 制定者在vuejs(2)

Vue.component('competetion-list', { 
    template: `<div><p>{{competition}}</p><p>{{totalCompetitions}}</p></div>`, 
    props: ['values'], 
    data: function() { 
    return {totalCompetitions: this.values.length} 
    }, 
    computed:{ 
    competition:{ 
     get: function(){ 
     return this.values.length; 
     }, 
     set: function(){ 
     this.totalCompetitions = this.values.length; 
     } 
    } 
    } 
}) 

和輸出我得到的是 -

15 
0 

所以,當我打電話competition它確實返回了values支柱的長度,但它沒有將長度設置爲totalCompetition並且顯示0是初始值。

但是,我能夠通過watch屬性更新totalCompetition

watch: { 
    values: function(){ 
    this.totalCompetetions= this.values.length 
    } 
} 

現在,我的問題是,爲什麼我不能通過computed制定者更新data屬性值,而getter方法可以返回相同?

+0

你認爲你的'set'函數在什麼時候被調用? –

回答

2

您忘記了this

computed:{ 
    competition:{ 
     get: function(){ 
     return this.values.length; 
     }, 
     set: function(){ 
     this.totalCompetitions = this.values.length; 
     } 
    } 
    } 

雖然從您發佈的代碼中找出您想要完成的功能還不清楚。現在,沒有什麼會執行set。通常,二傳手會接受一個值

set: function(value){ 
    this.totalCompetitions = value; 
} 

而且有你get工作過不同的值似乎是相互矛盾的工作。

可能你想要嗎?

data: function() { 
    return {competitions: this.values} 
    }, 
    computed:{ 
    totalCompetitions:{ 
     get: function(){ 
     return this.competitions.length; 
     } 
    } 
    } ,