子組件調用父組件的方法

1,直接在子組件中經過this.$parent.event來調用父組件的方法html

父組件測試

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

子組件this

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

2子組件裏用$emit向父組件觸發一個時間,父組件監聽這個事件就好了code

父組件component

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

子組件htm

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

3父組件把方法傳入子組件,在子組件裏直接調用這個方法事件

父組件ip

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

子組件it

<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>
相關文章
相關標籤/搜索