1. 程式人生 > >Vue子組件調用父組件的方法

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

scrip 觸發 The child vue console spa template fat

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

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