非父子傳值 :非父子組件之間的通信豌研,必須要有公共的實(shí)例(可以是空的)回怜,才能使用 $$emit 獲取 $on 的數(shù)據(jù)參數(shù)梭灿,實(shí)現(xiàn)組件通信
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<child></child>
<son></son>
</div>
<script src='js/vue.js'></script>
<script>
var bus=new Vue();
Vue.component('child',{//A
template:`
<div>
<h1>我是child組件</h1>
<button @click='sendMsg'>發(fā)送數(shù)據(jù)給son</button>
</div>
`,
data:function(){
return{
msg:'hello vue'
}
},
methods:{
sendMsg:function(){
bus.$emit('send',this.msg)
}
}
})
Vue.component('son',{//B
template:`
<div>
<h1>我是son組件</h1>
<a href=''>{{mess}}</a>
</div>
`,
data:function(){
return{
mess:''
}
},
mounted:function(){
bus.$on('send',msg=>{//箭頭函數(shù)
console.log(this);
this.mess=msg
})
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
生命周期 :
beforeCreate beforeCreate 創(chuàng)建前狀態(tài)
created created 創(chuàng)建完畢狀態(tài)
beforeMount beforeMount 掛載前狀態(tài)
mounted mounted 掛載結(jié)束狀態(tài)
beforeUpdate beforeUpdate 更新前狀態(tài)
updated updated 更新完成狀態(tài)
beforeDestroy beforeDestroy 銷(xiāo)毀前狀態(tài)
destroyed destroyed 銷(xiāo)毀完成狀態(tài)
生命周期.png
生命周期1.png