在Vue 3中,子组件调用父组件的方法可以通过使用$emit方法来实现。

首先,在父组件中定义一个方法,例如handleClick

// ParentComponent.vue

<template>
  <div>
    <button @click="handleClick">Click me</button>
    <ChildComponent @childClick="handleChildClick" />
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleClick() {
      console.log('Parent component method called');
    },
    handleChildClick() {
      console.log('Child component method called');
    }
  }
}
</script>

然后,在子组件中,通过$emit方法触发父组件的方法:

// ChildComponent.vue

<template>
  <div>
    <button @click="handleClick">Click me</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('childClick');
    }
  }
}
</script>

当子组件中的按钮被点击时,handleClick方法会被调用,并通过$emit方法触发父组件中的handleChildClick方法。

vue 3 setup 子组件调用父组件方法

原文地址: https://www.cveoy.top/t/topic/i9Am 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录