当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue组件父子间通信之综合练习(聊天室)

vue组件父子间通信之综合练习(聊天室)

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了vue组件父子间通信之聊天室的具体代码,供大家参考,具体内容如下

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网