【发布时间】:2019-12-10 06:56:11
【问题描述】:
我目前正在使用 laravel 创建一个网站,并使用 vue 创建了一个评论系统。我成功地发布了 cmets,但在编辑和删除特定评论时遇到问题。我试图以某种方式检索每个评论的 id,以便我可以创建一个类似于下图中的 postComment() 的方法来删除或编辑特定评论。有谁知道如何做到这一点? 提前致谢
这是我的帖子页面,其中包含帖子和附加的 cmets
<script>
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);
});
},
}
});
</script>
【问题讨论】:
-
这取决于从 API 返回的响应中的内容。在调用 getComments 之后,您将一个数组分配给“cmets”.. 因此,如果这是一个对象数组,您将通过 this.comment.id 访问评论 ID(如果存在),当使用 v-for 循环通过 cmets 时指示。这里没有足够的信息来提供适当的帮助
-
@paddyfields 当调用 getComment() 方法时,我会得到评论的文本、撰写评论的用户以及提交的日期和时间,并使用 @{{ }}。当我输入@{{comment.id}}时,我可以让评论ID显示在每个评论上,但我试图将它分配给一个变量,以便我可以使用它,但不幸的是我找不到方法,我不知道我能不能做到。如果我理解正确你所说的是在我将创建的 deleteComment() 方法中,我需要创建一个 v-for 指令?
-
假设您要删除评论,创建一个名为 deleteComment 的新方法,您可以通过 html 模板中删除按钮的 onclick 传递 id,例如)delete comment ...然后将注释 id 传递给您的方法,您可以在其中进行 API 调用并处理删除。 V-for 用在模板中而不是方法中,但如果你设法循环出 cmets,听起来你已经在这样做了
-
@paddyfields 我试过了,但没用。我添加了一个按钮“”,它传入了评论 ID,我创建了一个方法 deleteComment(comment .id) 接受 comment.id 然后我添加了 "axios.delete('api/posts/'+this.post.id+'/comment'+this.comment.id) .then((response) => { this.commentBox = ''; });"。但它没有用,我在猜测,因为它无法识别评论 ID,但我不确定