无法使用vuejs中的“计算”设置器更新“数据”(2)

时间:2017-03-16 16:24:16

标签: javascript vue.js vuejs2

我有这段代码 -

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,这是启动值。< / p>

但是,我能够通过totalCompetition属性更新watch

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

现在,我的问题是,为什么我不能通过data设置器更新computed属性值,而getter可以返回相同的值?

1 个答案:

答案 0 :(得分:3)

你忘了this

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

根据您发布的代码,目前还不清楚您要完成的任务。现在,没有什么可以执行set。通常,setter会接受一个值

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

让你的get工作不同的价值看起来像是在交叉目的。

可能你想要?

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