本文主要为大家详细介绍了vue组件父子间通信之综合练习聊天室制作,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>组件父子间通信之综合练习</title>
<script src="js/vue.js"></script>
</head>
<body>
<p id="container">
<p>{{msg}}</p>
<chat-room></chat-room>
</p>
<script>
// 创建父组件
vue.component("chat-room",{
//data属性中的chatlist保存用户聊天信息
data:function(){
return{
chatlist:[]
}
},
template:`
<p>
//假的聊天室
<h1>假的聊天室</h1>
<user-component username="rose"></user-component>
<user-component username="jack"></user-component>
//显示用户的聊天信息
<ul>
<li v-for="tmp in chatlist">{{tmp}}</li>
</ul>
</p>
`
})
//创建子组件
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:`
<p>
<label>{{username}}</label>
<input type="text" v-model="userinput"/>
<button @click="sendchat">发送</button>
</p>
`
})
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>
<p id="container">
<chat-room></chat-room>
</p>
<script>
vue.component('chat-room',{
methods:{
recvmsg:function(msg){
console.log("在父组件中接收子组件传来的数据"+msg);
this.chatlist.push(msg);
}
},
data: function () {
return {
chatlist:[]
}
},
template:`
<p>
<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>
</p>
`
})
vue.component('user-component',{
props:['username'],
data: function () {
return {
userinput:''
}
},
methods:{
sendtofather: function () {
//触发tofatherevent的事件,把input中
//用户输入的数据发送
this.$emit("sendtofather",this.username+":"+this.userinput);
}
},
template:`
<p>
<label>{{username}}</label>
<input type="text" v-model="userinput"/>
<button @click="sendtofather">发送</button>
</p>
`
})
new vue({
el: '#container',
data: {
msg: 'hello vue'
}
})
</script>
</body>
</html>
相关推荐:
swoole和websocket简单聊天室实现方法
php怎样开发聊天室
html5新技术socket.io实现聊天室的方法
以上就是vue组件父子间通信实现聊天室实例详解的详细内容。