将变量传递给 button vue js laravel



我正在尝试将 v-for 中的特定注释的变量 (id( 传递给呈现为刀片语法的按钮。我设法发布并获取评论,但我目前正在尝试根据他们的 ID 删除特定的评论。我一直在努力让它工作,但我不断收到这个错误

"vue.js:634 [Vue 警告]:v-on 处理程序中的错误:"类型错误:无法读取 属性 'id' 的未定义">

"类型错误: 无法读取未定义的属性'id'">

有人知道如何解决问题吗?

这是我的网页

<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>

这是我的 vue 脚本,我正在尝试传递评论的 id

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

deleteComment方法中,您将 id 指定为this.comment.id但尚未在数据对象中绑定comment,这就是您收到 TypeError 的原因。

此外,您将 id 作为参数传递给您的 deleteComment 方法,以便替换:

this.comment.idid应该可以解决问题。

最新更新