vue子組件調用父組件的方法


第一種方法是直接在子組件中通過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>

 

第二種方法是在子組件里用$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');

      }

    }

  };

</script>

 

第三種是父組件把方法傳入子組件中,在子組件里直接調用這個方法

 

父組件

<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>

 

三種都可以實現子組件調用父組件的方法,但是效率有所不同,根據實際需求選擇合適的方法

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM