【www.bbyears.com--SEO综合】
本文实例为大家分享了vue组件父子间通信之聊天室的具体代码,供大家参考,具体内容如下
组件父子间通信之综合练习
<script src="js/vue.js"></script>
{{msg}}
<script>
// 创建父组件
Vue.component("chat-room",{
//data属性中的chatList保存用户聊天信息
data:function(){
return{
chatList:[]
}
},
template:`
//假的聊天室
假的聊天室
//显示用户的聊天信息
{{tmp}}
`
})
//创建子组件
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:`
`
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
组件间通信综合练习:
(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接收到数据显示在列表中
代码:
<script src="js/vue.js"></script>
<script>
Vue.component("chat-room",{
methods:{
recvMsg:function(msg){
console.log("在父组件中接收子组件传来的数据"+msg);
this.chatList.push(msg);
}
},
data: function () {
return {
chatList:[]
}
},
template:`
假的聊天室
{{tmp}}
`
})
Vue.component("user-component",{
props:["userName"],
data: function () {
return {
userInput:""
}
},
methods:{
sendToFather: function () {
//触发toFatherEvent的事件,把input中
//用户输入的数据发送
this.$emit("sendToFather",this.userName+":"+this.userInput);
}
},
template:`
`
})
new Vue({
el: "#container",
data: {
msg: "Hello Vue"
}
})
</script>
本文来源:http://www.bbyears.com/seo/141521.html