1. 程式人生 > 實用技巧 >洛谷基礎演算法

洛谷基礎演算法

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

子元件:

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

第二種方法是在子元件裡用$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>
parent

子元件:

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

第三種是父元件把方法傳入子元件中,在子元件裡直接呼叫這個方法

父元件:

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

子元件:

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