首页 > 解决方案 > 查找模板引用最近的父 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.jsvuejs3vue-composition-api

解决方案


如果您想要最近的 vue 父级,您可以简单地使用

ref().$parent // Not sure if syntax is same in vue3

ref().$parent将获得第一个 vuecomponent,它是您放置的 ref 的父级。


推荐阅读