子组件控制父组件的事件

74 阅读1分钟

子组件

<template>
  <button @click="callParentMethod">调用父组件方法</button>
</template>

<script>
export default {
  methods: {
    callParentMethod() {
      this.$emit('call-parent-api');
    }
  }
}
</script>

父组件

<template>
  <div>
    <ChildComponent @call-parent-api="parentMethod" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    parentMethod() {
      // 调用父组件的接口或方法
      this.someApiCall();
    },
    someApiCall() {
      // 父组件的接口或方法实现
      console.log('父组件接口被调用');
    }
  }
}
</script>