当前位置: 首页 > 知识库问答 >
问题:

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

昌山
2023-05-18
<Parent ref="">
    <Children/>
</Parent>

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

共有1个答案

朱翔
2023-05-18

需要用 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这样的设计也可以减少不必要暴露的组件方法。

 类似资料:
  • 父组件 子组件 为什么执行getSonData的时候,无法获取到子组件的data?sonRef.value.data只能在onMounted内使用吗?不能在父组件的方法里执行?

  • vue3中子组件向父组件传值 在传值的时候为什么只能在声明一个方法的时候传递,而不能在定义click的时候传递呢

  • 本文向大家介绍如何在子组件中访问父组件的实例?相关面试题,主要包含被问及如何在子组件中访问父组件的实例?时的应答技巧和注意事项,需要的朋友参考一下 vue中如果父组件想调用子组件的方法,可以在子组件中加上ref,然后通过this.$refs.ref.method调用(https://www.cnblogs.com/jin-zhe/p/9523029.html) Vue中子组件调用父组件的方法,这里

  • 我有一个父组件[MainLayout],它有一个子组件[ListItems],并且有多个子组件[ListItem]。 谢谢你的回答!

  • 我有一个父组件从API获取一些数据,并将数据存储在状态中,然后将其传递给子组件,如下所示: 在我的子组件中,我有两个问题,一个是:我想在componentDidMount中接收一个道具(ratingsAverage),但在render()函数中接收ratingsAverage时未定义。另一个是:在我的render()函数中,我只能接收非对象或数组的数据,当我接收到一个对象并希望访问该对象的属性时,

  • 我有一个要导入页面的组件: 在页面上,我呈现组件