點擊前后對比圖:
body:
<div id="app">
<my-father></my-father>
</div>
js:
<script>
//父組件
Vue.component('my-father',{
template:
`
<div>
<h1>{{mess}}</h1>
<my-child v-on:send='Msg'></my-child>
</div>
`,
data:function(){
return{
mess:''
}
},
methods:{
//父組件接收子組件傳過來的值 值為txt
Msg:function(txt){
this.mess=txt
}
}
})
//子組件
Vue.component('my-child',{
template:
`
<button @click='sendToFather'>傳值給父元素</button>
`,
data:function(){
return{
message:'我是子組件躏敢,給父組件傳值'
}
},
methods:{
sendToFather:function(){
// 自定義事件,傳輸?shù)臄?shù)據(jù)
this.$emit('send',this.message)
}
}
})
new Vue({
el:'#app'
})
</script>