html 代码:
<div id='app'>
<my-father></my-father>
</div>
js代码:
<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>
效果图:
当点击按钮,子组件中的内容会传给父组件
小练习
效果图:
在输入框里输入内容后,点击按钮 输入内容就显示在父组件里了,
html代码:
<div id='app'>
<my-father></my-father>
</div>
js 代码:
<script src='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>
子传父 对话小练习:
html代码如下:
<div id='app'>
<chat-room></chat-room>
</div>
js代码如下:
<script src='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>