效果图:

body部分:
<div id="itany">
<my-father></my-father>
</div>
js部分:
<script src="js/vue.js"></script>
<script>
// 父组件
Vue.component('my-father',{
template:`
<div>
<ul>
<li v-for='(value,index) in chatcont'>{{value}}</li>
</ul>
<my-child @sendFather='rcvMsg' userName='Tom'></my-child>
<my-child @sendFather='rcvMsg' userName='Jack'></my-child>
</div>
`,
data:function(){
return{
chatcont:[]
}
},
methods:{
rcvMsg:function(txt){
// 给数组添加元素
this.chatcont.push(txt)
}
}
})
//子组件
Vue.component('my-child',{
props:['userName'],
template:`
<div>
<label>{{userName}}</label>
<input type='text' v-model='msg'>
<button @click='add'>发送</button>
</div>
`,
data:function(){
return{
msg:''
}
},
methods:{
add:function(){
this.$emit('sendFather',this.userName+':'+this.msg)
this.msg=''
}
}
})
new Vue({
el:"#itany"
})
</script>
网友评论