<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { box-sizing: border-box; } .form-group { margin-bottom: 10px } .form-group input { width: 100%; padding: 5px 10px; } .form-group textarea { padding: 5px 10px; width: 100%; height: 100px; } .form-group input, .form-group textarea { font-size: 16px; } </style> </head> <body> <div id="app"> <comment-app></comment-app> </div> <script src="./vue.js"></script> <script> /* 父子通信 两个子父通信 将commentApp中的comments传递给commentList 点击commentInput中的发布按钮,将comment对象发送给commentApp (comment对象需要拷贝一个新的) 点击commentList中的删除按钮,将index发送给commentApp (commentApp接受到之后删除对应的评论) */ /* CommentApp CommentInput CommentList */ // 创建 const CommentApp = { template: ` <div> <CommentInput @add:comment="addComment"></CommentInput> <hr> <CommentList :comments="comments" @del:comment="delComment"></CommentList> </div> `, data () { return { comments: [] } }, methods: { addComment (comment) { // 我们这里的参数是comment 未来子组件就需要传一个comment this.comments.unshift(comment) }, delComment (index) { console.log(index) this.comments.splice(index, 1) } } } // 创建CommnetInput const CommentInput = { template: ` <div> <div class="form-group"> <input type="text" v-model="comment.username"> </div> <div class="form-group"> <textarea v-model="comment.content"></textarea> </div> <div class="form-group"> <button @click="sendComment">发布</button> </div> </div> `, data () { return { comment: { username: '', content: '' } /* username: '', content: '' */ } }, methods: { sendComment () { // 调用$emit() /* Object.assign({}, 对象) 将对象拷贝到参数1中的{}中生成一个新的对象 */ // this.$emit('add:comment', JSON.parse(JSON.stringify(this.comment))) if (this.comment.username && this.comment.content) { this.$emit('add:comment', Object.assign({}, this.comment)) this.comment.content = "" } } } } // 创建CommentList const CommnetList = { template: ` <div> <div v-if="!comments.length">暂无评论</div> <ul v-else> <li v-for="(comment, index) in comments" :key="index"> <span>{{comment.username}}</span> <p>{{comment.content}}</p> <button @click="del(index)">删除</button> </li> </ul> </div> `, props: { comments: Array }, methods: { del (index) { // console.log(index) // 触发自定义事件 this.$emit('del:comment', index) } } } Vue.component('CommentApp', CommentApp) Vue.component('CommentInput', CommentInput) Vue.component('CommentList', CommnetList) const app = new Vue({ el: '#app' }) </script> </body> </html>