我正在使用laravel 5.4和vue 2.0。我需要插入像facebook这样的父帖的评论。 我想将'post 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>
提前感谢!!
答案 0 :(得分:1)
由于您使用:post="post.id"
传递道具,因此在注释输入组件中声明道具属性,如下所示:
<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
我正在重构你的代码,以便它易于理解
将postId作为名为postId
的道具传递,以便轻松识别
<comment-input :postId="post.id" @completed='addRecentComment'></comment-input>
然后在你的评论输入组件中声明像这样的道具属性
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>
您在输入时不需要exta @keyup
事件,因为在表单内按文本输入的默认行为将提交表单
您可以将输入的v-model
绑定到数据选项中的空注释