2016-12-06 36 views
12

这里是我的数据:爱可信不能设置数据

data: function(){ 
    return { 
     contas: [{id: 3, 
      nome: "Conta de telefone", 
      pago: false, 
      valor: 55.99, 
      vencimento: "22/08/2016"}] //debug test value 
    }; 
}, 

这是我的GET请求:

beforeMount() { 
    axios.get('http://127.0.0.1/api/bills') 
     .then(function (response) { 
      console.log("before: " + this.contas); 
      this.contas = response.data; 
      console.log("after: " + this.contas); 
     }); 
}, 

的问题是我无法从axios.get()中访问this.contas。我试过Vue.set(this, 'contas', response.data);window.listaPagarComponent.contas = response.data;没有成功。

我的控制台显示:

before: undefined 
after: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object] 

但只有Vue公司Devtools显示:

contas: Array[1] 
    0: Object 
    id: 3 
    nome: "Conta de telefone" 
    pago: false 
    valor: 55.99 
    vencimento: "22/08/2016" 

这里是我的full code

+1

尝试使用'()创建'挂钩,而不是'beforeMount( )'。如果你已经在contas数组中定义了一些数据,那么我认为你应该做array.push。 –

+1

好的,你可以在数据模型中创建新的数组,并设置响应数据吗?然后结帐,项目是否存储在数组中。不幸的是,我不使用Axios,我宁愿使用Vue资源。 –

+1

@Belmin没有什么变化......它只是一个调试测试值。我不想要这个价值。问题是我不能使用'this.contas'来引用组件的数据'contas'。没有功能起作用。我认为axios是一个“对象”,所以当我使用'this'时,它指的是axios。 –

回答

45

在选项功能,如datacreated,VUE结合this为我们的视图模型实例,所以我们可以使用this.contas,但在里面then功能,this不绑定。

所以你需要保存视图模型像(created意味着该组件的数据结构组装,这就足够了这里,mounted将延迟操作更多):

created() { 
    var self = this; 
    axios.get('http://127.0.0.1/api/bills') 
     .then(function (response) { 
       self.contas = response.data; 
       }); 
} 

或者你可以使用箭头功能ES6标准,如果你只着眼于支持现代浏览器(或使用像巴贝尔一transpiler),如:

created() { 
    axios.get('http://127.0.0.1/api/bills') 
     .then((response) => { 
       this.contas = response.data; 
       }); 
} 

this里面的箭头函数是根据词法上下文绑定的,也就是说上面代码片段中的thiscreated中的this相同,这就是我们想要的。

+1

谢谢!这解决了我的问题! –

+0

Hooray!这也解决了我的问题......谢谢。不管我多少次学习和理解“这个”,它总会给我造成问题。 –

0

是的,我想我需要发表另一个问题,因为现在的问题是不同的。但为了能够访问this.contas我刚刚用mounted: function() {}替换了beforeMount() {}

6

为了能够访问this.contas内axios.get()你需要绑定“这种”保持变量的使用范围的:

mounted() { 
    axios.get('http://127.0.0.1/api/bills') 
    .then(function (response) { 
     console.log("before: " + this.contas); 
     this.contas = response.data; 
     console.log("after: " + this.contas); 
    }.bind(this)); 
}