vue3子slot组件如何获取父组件的实例?

<Parent ref="">
    <Children/>
</Parent>

如何在Children内部拿到父级的ref? 父级是不同的组件

阅读 3.6k
1 个回答

需要用 provide & inject 来实现:

  1. 在父组件中 提供组件 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> 
  1. 在子组件中 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> 
  1. 进阶优化 

如果是组件库 或者 长期维护的项目 建议使用 一个公共的 Symbol 保存常量

// provide-symbol
 export const PARENT_SYMBOL = Symbol(); 

最终可以较为方便的在 setup 中迁移 vue2 原有逻辑。同样 vue3这样的设计也可以减少不必要暴露的组件方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题