我正在使用Vue资源,并尝试基于来自上一次AJAX调用的(假定绑定的)数据进行一次AJAX调用。
我正在尝试将调用/me的数据绑定到userDetails属性(似乎工作正常),并将userDetails.id传递给下一个函数(this.fetchMyProjects())以获取该用户的项目。(不工作)。
WHen我将ID硬编码到this.fetchMyProjects()中,它绑定得很好,问题是对this.userDetails对象的引用-它在这个上下文中是未定义的。
我不明白为什么我不能访问一个我认为是绑定的属性。有没有人能对我做错了什么提供一些指导?
代码:
new Vue({
el : 'body',
data : {
projects: [],
userDetails: {},
},
created : function(){
this.fetchMyUserDetails();
this.fetchMyProjects();
},
methods : {
fetchMyUserDetails : function(){
this.$http.get('/me', function(resp){
this.userDetails = resp.data;
}).bind(this);
},
fetchMyProjects: function(){
this.$http.get('/projects/user/' + this.userDetails.id, function(projects){
this.projects = projects.data;
}).bind(this);
},
}
});发布于 2016-03-22 23:48:33
你有一个放错地方的)。需要在函数上直接调用.bind(),在本例中是在}上
this.$http.get('/me', function(resp){
this.userDetails = resp.data;
}.bind(this));发布于 2016-03-23 05:22:39
这是可行的:
new Vue({
el : 'body',
data : {
projects: [],
userDetails: {},
},
created : function(){
this.fetchMyUserDetails();
// this.fetchMyProjects(); // Needed to chain it into fetchMyUserDetails()
},
methods : {
fetchMyUserDetails : function(){
this.$http.get('/me', function(resp){
this.userDetails = resp.data;
this.fetchMyProjects(); // Works!
}).bind(this);
},
fetchMyProjects: function(){
this.$http.get('/projects/user/' + this.userDetails.id, function(projects){
this.projects = projects.data;
}).bind(this);
},
}
});https://stackoverflow.com/questions/36146742
复制相似问题