示例场景:
1.应用于我的个人博客网站文章详情页,内置评论功能,评论区位于子组件,评论列表位于父组件
2.父组件会将从服务器获取文章信息(如文章id,文章相关信息),并将文章id发送给子组件,用于子组件利用id将评论内容发送至数据库指定位置存储
3.子组件发送评论内容后,子组件还需要将新评论发送至父组件的评论列表区更新视图
子组件:
父组件:
方式1:父组件通过props向子组件传值,子组件通过$emit自定义事件向父组件传值
父组件:
<!--封装好的评论区-->
<comment :id='id'
@updateComments="updateComments">
</comment><!--在子组件绑定传递的数据或事件-->
<!--评论列表-->
<ul v-for="(items,index) in comments" v-bind:key="index">
<li class="comment-item">
<section>
<el-avatar icon="el-icon-user-solid" :size="60"></el-avatar>
</section>
<section class="item-right">
<p>用户:{{items.nickname}}</p>
<p>Ta说:{{items.body}}</p>
</section>
</li>
</ul>
<script>
import comment from '../components/Comment'
export default {
components: {
comment
},
data () {
return {
comments: [],
id: this.$route.params.id //此处的id是从首页跳转路由获取的
}
},
methods: {
updateComments (newComments) { //当子组件发送新评论时触发此函数,更新数据且更新视图
this.comments.push(newComments)
}
}
</script>
子组件:
<template>
<section class="addcomment">
<p class="addcomment-header">
<i class="el-icon-chat-line-square"> 欢迎评论</i>
</p>
<div class="form-style">
<el-form label-position="top" label-width="80px" v-model="comment">
<el-form-item label="昵称:">
<el-input placeholder="请输入您的昵称" v-model="comment.nickname"></el-input>
</el-form-item>
<el-form-item label="评论内容:">
<el-input placeholder="请输入您的评论内容" v-model="comment.body"></el-input>
</el-form-item>
</el-form>
<el-button @click="submitComment()">提交评论</el-button>
</div>
</section>
</template>
<script>
import api from '../axios' //获取封装好的axios函数以向服务器通信
export default {
props: ['id'], //向父组件获取文章id
data () {
return {
comment: {
nickname: '',
body: ''
}
}
},
methods: {
submitComment () {
let obj = {
id: this.id,
comment: this.comment
}
api.addComment(obj).then(res => { //向服务器发送评论内容
const newComments = this.comment //获取新评论
this.$emit('updateComments', newComments) //向父组件通信,发送新评论,并触发更新视图事件
})
}
}
}
</script>
总结:
父组件向子组件通信:在子组件标签通过v-bind(语法糖为:)绑定需要传递的数据(数字、字符串、对象、数组等),子组件内使用props接收数据
<script>
props: ['id1','id2'] //无限定
props: {
id:{
type : String
default : 默认值 //若没传值则为默认值
require : true/false //是否必须传值
}
}
//数据类型为对象或数组时
props: {
id:{
type : String
default(){
return{}/[]
} //若没传值则为默认值
require : true/false //是否必须传值
}
}
</script>
子组件向父组件通信:在子组件通过v-on(语法糖为@)绑定父组件的事件,子组件内通过$emit自定义事件向父组件传递数据
<script>
this.$emit('父组件事件','需传递的数据')
</script>