【发布时间】:2018-04-22 01:33:00
【问题描述】:
我正在尝试呈现笔记列表,并且在该列表中我想根据存储在笔记表中的 user_id 包含笔记的用户名。我有类似的东西,但目前它正在记录一个错误,指出 Cannot read property 'user_id' of undefined,我明白了原因。
我的问题是,在 Vue 中如何执行这样的操作?
模板:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{user.name}}</em>
</div>
脚本:
methods:{
fetchNotes(id){
return this.$http.get('http://api/notes/' + id )
.then(function(response){
this.notes = response.body;
});
},
fetchUser(id){
return this.$http.get('http://api/user/' + id )
.then(function(response){
this.user = response.body;
});
}
},
created: function(){
this.fetchNotes(this.$route.params.id)
.then( () => {
this.fetchUser(this.note.user_id);
});
}
更新:
我修改了我的代码,使其看起来像下面的示例,我得到了更好的结果,但还不是 100%。使用此代码,它在第一次呈现视图时工作,如果我在此组件之外导航然后返回,它会失败......如果我刷新页面,同样的事情。
我得到的错误是:[Vue warn]: Error in render: "TypeError: Cannot read property 'user_name' of undefined"
注意 console.log... 它每次都按预期返回对象,但正如我提到的,如果刷新页面或导航过去然后返回此组件,我会得到错误和正确的日志。
模板:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.user_name}}</em>
</div>
脚本:
methods:{
fetchNotes(id){
return this.$http.get('http://api/notes/' + id )
.then(function(response){
this.notes = response.body;
for( let i = 0; i < response.body.length; i++ ) {
let uId = response.body[i].user_id,
uNote = this.notes[i];
this.$http.get('http://api/users/' + uId)
.then(function(response){
uNote.user = response.body;
console.log(uNote);
});
}
});
},
}
【问题讨论】:
-
this未绑定在您的.then回调中。你能用箭头函数代替function函数吗? -
@RoyJ 哪个回调?两个都?我尝试将两个回调都更改为箭头函数,但行为仍然相同,当我刷新页面时它会中断并收到错误消息,但 console.log 显示正确的数据。
-
你最里面的回调没有使用
this,所以没关系。第一个回调使用this,它是未绑定的,所以它不会正确设置notes。导航是否会清除this.notes?导航返回调用created钩子吗? -
进行了更改,但仍然没有骰子。导航或刷新确实会触发创建的钩子并按应有的方式记录
this.notes。我注意到的另一个有趣的事情是,如果我将模板{{ note.user.user_name }}更改为{{ note.user.user_email }}它会中断,它会刷新页面并正确显示,但是一旦我离开并返回相同的问题。如果我再把它改回{{ note.user.user_name }},一切都会好起来的。 -
另外,如果我注释掉 for 循环和模板中对用户的任何引用,即:
{{ note.user.user_name }},这一切都像魅力一样。