1. 程式人生 > >vue元件通訊之評論

vue元件通訊之評論

<!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>