【发布时间】:2020-04-05 22:27:36
【问题描述】:
我正在尝试将 v-for 中特定注释的变量 (id) 传递给呈现为刀片语法的按钮。我设法发布并获取了 cmets,但我目前正在尝试根据他们的 id 删除特定的 cmets。我一直在努力如何让它工作,但我不断收到这个错误
"vue.js:634 [Vue 警告]:v-on 处理程序中的错误:"TypeError:无法读取 未定义的属性 'id'"
和
"TypeError: 无法读取未定义的属性 'id'"
有人知道如何解决这个问题吗?
这是我的html
<div class="media" style="margin-top:20px;" v-for="comment in comments">
<div class="media-left">
<a href="#">
<img class="media-object" src="http://placeimg.com/80/80" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">@{{comment.user.name}} said...</h4>
<p>
@{{comment.text}}
</p>
<span style="color: #aaa;">on @{{comment.created_at}}</span>
<p>
@{{comment.id}}
</p>
<button class="btn btn-default" v-on:click="deleteComment('@{{comment.id}}')">Delete comment</button>
这是我试图传递评论 id 的 vue 脚本
const app = new Vue({
el:'#root',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!},
},
mounted() {
this.getComments();
},
methods: {
getComments(){
axios.get('/api/posts/'+this.post.id+'/comments')
.then((response) => {
this.comments = response.data
})
.catch(function (error) {
console.log(error);
});
},
postComment(){
axios.post('/api/posts/'+this.post.id+'/comment', {
api_token: this.user.api_token,
text: this.commentBox
})
.then((response) => {
this.comments.unshift(response.data);
this.commentBox = '';
})
.catch(function (error) {
console.log(error);
});
},
deleteComment(id){
axios.delete('api/posts/'+this.post.id+'/comment'+this.comment.id)
.then((response) => {
this.commentBox = '';
return 'delete successfull';
})
.catch(function (error) {
console.log(error);
});
},
enter code here
【问题讨论】:
-
使用 this.post[id] 和 this.comment[id] 代替,因为你的变量没有在 deleteComment 函数中使用。
-
@Jake 感谢您的快速回复。我试过了,但我得到了这些错误 vue.js:634 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property '{{comment.id}}' of undefined" 和 "Cannot read property '{ {comment.id}}' 未定义”。我假设它是我将变量传递给按钮的方式,或者 id 未被识别。
-
您确定您的评论有一个以 id 开头的 id 吗?当你
console.log(this.comments[id])在你的函数中打印什么? -
@Jake 是的,我的评论有 id、text、date、userid 和 postid,这是评论附加到的帖子的 id。
-
您的一些 axios 调用使用 '/cmets' 和其他 '/comment' 是否正常?您的数据结构如何? cmets.comment.id ?
标签: laravel vue.js post axios comments