VUE2.0 觀察者模式、父子組件調用

一、觀察者模式

  1. 事件發佈 : this.$root.eventHub.$emit(事件名稱,傳遞的參數);
  2. 訂閱事件 : this.$root.eventHub.$on(事件名稱,(response)=>{ })
  3. 取消訂閱: 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 可訪問子組件屬性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章