需要用 provide & inject 来实现:在父组件中 提供组件 ref 以及 提供需要的 function// parent component <template> <div ref="root">parent</div> </template> <script setup> import { provide, ref } from 'vue'; // 父组件 ref 引用 export const root = ref(null); export function testFun() { console.log('parent/testFun') } const PARENT_PROVIDE = 'parentProvide' // 提供父组件 ref 引用 provide(PARENT_PROVIDE, root); // 提供父组件指定方法 provide(`${PARENT_PROVIDE}/testFun`, testFun); </script> 在子组件中 inject<template> <div>child<div> </template> <script setup> import { inject, onMounted } from 'vue'; const PARENT_PROVIDE = 'parentProvide' onMounted(() => { // 注入父组件 ref const parent = inject(PARENT_PROVIDE); console.log('parent root:' parent); // 注入父组件指定方法 const parentTestFun = inject(`${PARENT_PROVIDE}/testFun`); parentTestFun(); }) </script> 进阶优化 如果是组件库 或者 长期维护的项目 建议使用 一个公共的 Symbol 保存常量// provide-symbol export const PARENT_SYMBOL = Symbol(); 最终可以较为方便的在 setup 中迁移 vue2 原有逻辑。同样 vue3这样的设计也可以减少不必要暴露的组件方法。
需要用 provide & inject 来实现:
如果是组件库 或者 长期维护的项目 建议使用 一个公共的 Symbol 保存常量
最终可以较为方便的在 setup 中迁移 vue2 原有逻辑。同样 vue3这样的设计也可以减少不必要暴露的组件方法。