vue組件父子間通信之綜合練習--假的聊天室
阿新 • • 發佈:2017-11-02
ner name type 屬性 urn ejs rec 用戶輸入 for
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>組件父子間通信之綜合練習</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <chat-room></chat-room></div> <script> // 創建父組件 Vue.component("chat-room",{ //data屬性中的chatList保存用戶聊天信息 data:function(){ return{ chatList:[] } }, template:` <div> //假的聊天室 <h1>假的聊天室</h1> <user-component userName="Rose"></user-component> <user-component userName="Jack"></user-component> //顯示用戶的聊天信息 <ul> <li v-for="tmp in chatList">{{tmp}}</li> </ul> </div> ` }) //創建子組件 Vue.component("user-component",{ props:["userName"], //通過v-model把用戶輸入的數據保存到userInput數組 data:function(){ return { userInput:[] } }, methods:{ //把用戶輸入的數據以及用戶名label信息push給chatList數組 sendChat:function(){ this.$parent.chatList.push(this.userName+":"+this.userInput); //情況input框 this.userInput =" "; } }, template:` <div> <label>{{userName}}</label> <input type="text" v-model="userInput"/> <button @click="sendChat">發送</button> </div> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
組件間通信綜合練習:
(props down,events up)
有2個組件:chat-room,user-component
user-component是由label input button構成
chat-room是由兩個user-component和一個列表構成
①在chat-room調用user-component指定label的名字
②在user-component,
點擊按鈕時,將當前用戶輸入的信息發送給chat-room組件,chat-room接收到數據顯示在列表中
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <script src="js/vue.js"></script> <title></title> </head> <body> <div id="container"> <chat-room></chat-room> </div> <script> Vue.component(‘chat-room‘,{ methods:{ recvMsg:function(msg){ console.log("在父組件中接收子組件傳來的數據"+msg); this.chatList.push(msg); } }, data: function () { return { chatList:[] } }, template:` <div> <h1>假的聊天室</h1> <ul> <li v-for="tmp in chatList"> {{tmp}} </li> </ul> <user-component userName="Lucy" @sendToFather="recvMsg"></user-component> <user-component userName="Merry" @sendToFather="recvMsg"></user-component> </div> ` }) Vue.component(‘user-component‘,{ props:[‘userName‘], data: function () { return { userInput:‘‘ } }, methods:{ sendToFather: function () { //觸發toFatherEvent的事件,把input中 //用戶輸入的數據發送 this.$emit("sendToFather",this.userName+":"+this.userInput); } }, template:` <div> <label>{{userName}}</label> <input type="text" v-model="userInput"/> <button @click="sendToFather">發送</button> </div> ` }) new Vue({ el: ‘#container‘, data: { msg: ‘Hello Vue‘ } }) </script> </body> </html>
vue組件父子間通信之綜合練習--假的聊天室