下面是一个使用 Vue 3 的 setup 函数创建父子组件,并使用自定义回调的示例:

父组件代码:

<template>
  <div>
    <h2>Parent Component</h2>
    <child-component :callback='callbackFunction' />
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  setup() {
    const callbackFunction = (data) => {
      console.log('Parent received data from child:', data)
      // 在这里处理从子组件传来的数据
    }

    return {
      callbackFunction
    }
  }
}
</script>

子组件代码:

<template>
  <div>
    <h3>Child Component</h3>
    <button @click='sendDataToParent'>Send Data to Parent</button>
  </div>
</template>

<script>
export default {
  props: {
    callback: {
      type: Function,
      required: true
    }
  },
  setup(props) {
    const sendDataToParent = () => {
      const data = 'Hello, Parent!'
      props.callback(data)
    }

    return {
      sendDataToParent
    }
  }
}
</script>

在父组件中,我们将一个名为 callbackFunction 的函数传递给子组件,作为子组件中按钮点击事件的回调函数。

在子组件中,我们使用 props 接收父组件传递的 callback 函数,并在 sendDataToParent 函数中调用该函数,并将数据作为参数传递。

当子组件中的按钮被点击时,sendDataToParent 函数将触发父组件的 callbackFunction 函数,并将数据传递给它。

父组件中的 callbackFunction 函数将在控制台中打印从子组件传来的数据,并在这里进行任何需要的处理。

Vue 3 Setup 函数父子组件自定义回调示例

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

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