问题
i am using laravel 5.4 and vue 2.0. I need to insert comments of parent posts like facebook. I want to pass 'post id' from parent to child template to insert comments of that parent post.
<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>
//comment-input template
<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>
thanks in advance !!
回答1:
Since you are passing a prop using :post="post.id"
declare a props property in your comment-input component like this:
<script>
export default {
props: ['post']
data() {
return {
form: new Form({comment: ''})
}
},
methods: {
onSubmit() {
this.form
.post('/comments')
.then(post => this.$emit('completed', comment));
}
}
}
</script>
Then you can use the prop in the component using this.post
I am refactoring your code a little bit so that it is easy to understand
Pass the postId as a prop named postId
so that it is easily recognizble
<comment-input :postId="post.id" @completed='addRecentComment'></comment-input>
Then in your comment-input component declare the props propert like this
props: ['postId']
and finally your comment-input component
<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>
you don't need exta
@keyup
event on input since the default behaviour of pressing enter in text input inside a form will submit you formyou can just bind the input's
v-model
to empty comment in your data option
来源:https://stackoverflow.com/questions/45098947/insert-child-comments-of-parent-post-vue-js