我正在使用 laravel 5.4 和 vue 2.0。我需要插入家长帖子的评论,例如 Facebook。 我想将“帖子 ID”从父模板传递到子模板以插入该父帖子的评论。
<div class="post-section" v-for="(post,index) in posts">
<div class="media-content" v-text='post.body'></div>
<button @click="getComments(post, index)" class="btn btn-link">Comments</button>
<div v-if='show' class="card comment" v-for='comment in post.comments'>
<span> {{comment.comment}}</span>
</div>
<comment-input :post="post.id" @completed='addRecentComment'></comment-input>
</div>
//评论输入模板
<template>
<form @submit.prevent='onSubmit'>
<div class="media-comment">
<input @keyup.enter="submit" type="text" v-model='form.comment' class="form-control" placeholder="comment...">
</div>
</form>
</template>
<script>
export default {
data() {
return {
form: new Form({comment: ''})
}
},
methods: {
onSubmit() {
this.form
.post('/comments')
.then(post => this.$emit('completed', comment));
}
}
}
</script>
提前致谢!!
最佳答案
由于您使用 :post="post.id"
传递 prop,因此在评论输入组件中声明 props 属性,如下所示:
<script>
export default {
props: ['post']
data() {
return {
form: new Form({comment: ''})
}
},
methods: {
onSubmit() {
this.form
.post('/comments')
.then(post => this.$emit('completed', comment));
}
}
}
</script>
然后您可以使用 this.post
在组件中使用该 prop
我正在稍微重构一下您的代码,以便它易于理解
将 postId 作为名为 postId
的 prop 传递,以便轻松识别
<comment-input :postId="post.id" @completed='addRecentComment'></comment-input>
然后在您的评论输入组件中声明 props 属性,如下所示
props: ['postId']
最后是你的评论输入组件
<template>
<form @submit.prevent='onSubmit'>
<div class="media-comment">
<input type="text" v-model='comment' class="form-control" placeholder="comment...">
</div>
</form>
</template>
<script>
export default {
props: ['postId'],
data() {
return {
comment: ''
}
},
methods: {
onSubmit() {
axios.post('api_url/' + this.postId, {comment: this.comment})
.then(response => {
this.$emit('completed', this.comment);
this.comment = ''; // reset back to empty
});
}
}
}
</script>
输入时不需要额外的
@keyup
事件,因为在表单内的文本输入中按 Enter 的默认行为将提交表单您可以将输入的
v-model
绑定(bind)到数据选项中的空注释
关于javascript - 插入父帖子vue js的子评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098947/