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>
效果图:
14a6b88c-9881-4551-9d9c-d85f95de66f2.png当点击按钮,子组件中的内容会传给父组件
e363710d-9666-4c47-a790-b29d460b88a6.png
小练习
效果图:
6578589b-11fb-48a3-95d8-82b192c6b562.png在输入框里输入内容后,点击按钮 输入内容就显示在父组件里了,
340168bb-53fb-4d31-9352-038fa1935da6.png
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>
子传父 对话小练习:
35f685a0-753b-410d-8aeb-c40a00117bcd.png
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>
网友评论