一、觀察者模式
- 事件發佈 : this.$root.eventHub.$emit(事件名稱,傳遞的參數);
- 訂閱事件 : this.$root.eventHub.$on(事件名稱,(response)=>{ })
- 取消訂閱: this.$root.eventHub.$off(事件名稱)
二、父子組件的調用
<!--子組件-->
<template>
<div @click="callParentFunction">點擊調用子組件方法</div>
<son-component ref="sonModal"></son-component>
</template>
<script>
export default{
data(){
return {
num:1
}
},
methods:{
/**
* 初始化數據
**/
init(){
},
/**
* 調用父組件方法
**/
callParentFunction(){
this.$parent.init();
//給父子屬性賦值
this.$parent.testNum =1;
}
}
}
</script>
<!--父組件-->
<template>
<div @click="callSonFunction">點擊調用子組件方法</div>
<son-component ref="sonModal"></son-component>
</template>
<script>
export default{
data(){
return {
messageList:[],
testNum:1
}
},
methods:{
/**
* 初始化數據
**/
init(){
this.messageList= [1,2,3];
},
/**
* 調用子組件方法
**/
callSonFunction(){
this.$refs.sonModal.init();
this.$refs.sonModal.num=2;
}
}
}
</script>
三、$children 返回的是一個組件集合 this.$children[i].data 可訪問子組件屬性