vue.js - 查找模板引用最近的父 Vue 组件(Vue 3)
问题描述
安装Vue模板引用时,我想获取最近的父 Vue 组件。这应该是通用的并且适用于任何模板引用,所以我把它放在一个组合函数中(但这只是一个实现细节)。
我有这个工作,但我的实现elem.__vueParentComponent
在迭代搜索元素的祖先时使用。在阅读我看到的 Vue源代码__vueParentComponent
时,仅启用了开发模式或在生产中启用了开发工具。因此,我不想依赖启用该标志。
我认为这可能使用 vnodes 来实现,但这并不容易通过谷歌搜索。这是我正在尝试做的一个例子:
function useNearestParentInstance(templateRef) {
function getNearestParentInstance(el) {
// code here
}
onMounted(() => {
const el = templateRef.value;
const instance = getNearestParentInstance(el);
// do something with instance
});
}
<template>
<div>
<SomeComponent>
<div>
<div ref="myElem"></div>
</div>
</SomeComponent>
</div>
</template>
<script>
export default {
setup() {
const myElem = ref();
// nearest would be SomeComponent's instance in this case
useNearestParentInstance(myElem);
...
}
}
</script>
解决方案
如果您想要最近的 vue 父级,您可以简单地使用
ref().$parent // Not sure if syntax is same in vue3
ref().$parent
将获得第一个 vuecomponent,它是您放置的 ref 的父级。
推荐阅读
- javascript - 使用 react-native-firebase-mlkit 时相机未检测到纵向模式下的文本?
- php - Laravel 5.6:页面由于不活动而过期
- java - 如何以编程方式设置 MultiSelectListPreference 的复选框值?
- git - 无法将提交推送到我的 git 存储库
- elasticsearch - 如何使用groovy脚本在elasticsearch中获取具有给定ID的特定文档是否存在
- azure - azure ad 中的 windows 应用程序需要注册
- android - 基于使用的主题的 BottomNavigationView 文本调整大小动画问题
- dynamics-crm - 功能区工作台在发布后自动添加两个命令
- delphi - 在 Delphi Tokyo 中不再使用 Form.PixelsPerInch
- wordpress - 如何在 woocommerce 订单状态更改时触发电子邮件?