一、子组件给父组件传值(1)
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-father",{
template:`
<div>
<h1>{{mess}}</h1>
<my-child @send='rcvMsg'></my-child>
</div>
`,
data:function(){
return{
mess:''
}
},
methods:{
rcvMsg:function(txt){
this.mess=txt
}
}
})
Vue.component('my-child',{
template:`
<button @click='sendToFather'>传给父元素</button>
`,
data:function(){
return{
msg:'我是子组件中的数据,要给父组件传值'
}
},
methods:{
sendToFather:function(){
// this.$emit('自定义事件名',要传输的数据)
this.$emit('send',this.msg)
}
}
})
new Vue({
el:"#app"
})
</script>
</body>
子组件给父组件传值(2)
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-father",{
template:`
<div>
<h1>我是父组件</h1>
<p>组组件传过来的数据:<b>{{mess}}</b></p>
<my-child @send='rcvMsg'></my-child>
</div>
`,
data:function(){
return{
mess:''
}
},
methods:{
rcvMsg:function(txt){
this.mess=txt
}
}
})
Vue.component('my-child',{
template:`
<div>
<h1>我是子组件</h1>
<input type='text' v-model='msg'> <button @click='sendMsg'>发送</button>
</div>
`,
data:function(){
return{
msg:''
}
},
methods:{
sendMsg:function(){
this.$emit('send',this.msg)
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
二、父子通信混合使用
<body>
<div id='app'>
<chat-room></chat-room>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('chat-room',{
template:`
<div>
<ul>
<li v-for="(value,index) in chatcont">{{value}}</li>
</ul>
<user @send='rcvMsg' userName='jack'></user>
<user @send='rcvMsg' userName='rose'></user>
</div>
`,
data:function(){
return{
chatcont:[],
}
},
methods:{
rcvMsg:function(txt){
this.chatcont.push(txt)
}
}
})
Vue.component('user',{
props:['userName'],
template:`
<div>
<label>{{userName}}</label>
<input type='text' v-model='msg'>
<button @click='sendMsg'>发送</button>
</div>
`,
data:function(){
return{
msg:''
}
},
methods:{
sendMsg:function(){
this.$emit('send',this.userName+":"+this.msg)
}
}
})
new Vue({
el:'#app'
})
</script>
</body>