天天看點

子元件調用父元件的方法和父元件調用子元件的方法

一.子元件調用父元件的方法

1.是直接在子元件中通過this.$parent.event來調用父元件的方法

父元件

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('測試');
      }
    }
  };
</script>
           

子元件

<template>
  <div>
    <button @click="childMethod()">點選</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$parent.fatherMethod();
      }
    }
  };
</script>
           

2.是在子元件裡用$emit向父元件觸發一個事件,父元件監聽這個事件

父元件

<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>  //父元件監聽
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {    //事件
        console.log('測試');
      }
    }
  };
</script>
           

子元件

<template>
  <div>
    <button @click="childMethod()">點選</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$emit('fatherMethod');//  $emit向父元件觸發事件
      }
    }
  };
  </script>
           

3.是父元件把方法傳入子元件中,在子元件裡直接調用這個方法

父元件

<template>
  <div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('測試');
      }
    }
  };
</script>
           

子元件

<template>
  <div>
    <button @click="childMethod()">點選</button>
  </div>
</template>
<script>
  export default {
    props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
  };
</script>
           

**

二.父元件調用子元件的方法

**

父元件

<template>
  <div>
  <div @click="fatherMethod"></div>
    <child ref="childRef"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
      this.$refs.childRef.childMethod()//父元件調用子元件的childMethod方法,顯示       
      }
    }
  };
</script>
           

子元件

<template>
  <div>
   <div v-if="isShow">child</div>
  </div>
</template>
<script>
  export default {
  data(){
     return {
     isShow:false
     }
  }
    methods: {
      childMethod() {   //
       this.isShow = !this.isShow
        }
      }
    }
};
</script>
           

繼續閱讀