1、子组件中通过 this.$parent.event 来调用父组件的方法。

父组件

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('调用父组件方法成功');
      }
    }
  };
</script>

子组件

2、在子组件里用 $emit向父组件触发一个事件,父组件监听这个事件。

父组件

<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('调用父组件方法成功');
      }
    }
  };
</script>

子组件

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

3、父组件把方法传入子组件中,在子组件里直接调用这个方法。

父组件

<template>
  <div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('调用父组件方法成功');
      }
    }
  };
</script>

子组件

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

转:vue子组件调用父组件的方法_tony康的博客-CSDN博客_vue子组件调用父组件中的方法

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐