简体   繁体   English

如何使用Vue.js获取呈现dom元素的组件

[英]How to get the component that rendered a dom element with Vue.js

How to get the component that rendered a dom element with Vue.js ? 如何使用Vue.js获取呈现dom元素的组件?

For example, suppose you want to retrieve which component "owns" a dom element that the user has selected, how would you do ? 例如,假设您要检索“拥有”用户选择的dom元素的组件,您将如何做? (it seems to be implemented in the dev tools, but I can't find a way neither in the documentation, neither on SO) (它似乎是在开发工具中实现的,但我在文档中和SO上都找不到方法)

(I mean, given the DOM element, I know how to retrieve what element is selected) (我的意思是,给定DOM元素,我知道如何检索选择的元素)

DISCLAIMER : This may not be the right solution for common use cases. 免责声明:对于常见的用例,这可能不是正确的解决方案。 Always prefer handling event & co. 总是喜欢处理事件和合作。 in the root component using direct sub-component reference if you can 如果可以的话,在根组件中使用直接子组件引用

I do not know if this is safe or officially supported, but assuming you're trying to access the component from some external-to-Vue code, this will return the VueComponent object for a given DOM element (substitute your own DOM selector as needed): 我不知道这是安全的还是得到正式支持,但是假设您尝试从外部到Vue的代码访问该组件,这将为给定的DOM元素返回VueComponent对象(根据需要替换您自己的DOM选择器):

document.getElementById('foo').__vue__

If used on the app's root element, it will instead return the Vue constructor object. 如果在应用程序的根元素上使用,它将返回Vue构造函数对象。

(This appears to work in both Vue 1.x and 2.x.) (这似乎在Vue 1.x和2.x中都适用。)

This is possibly not the most elegant solution, but you can use mixins to achieve this: 这可能不是最优雅的解决方案,但是您可以使用mixins实现此目的:

var elemOwner = {
  mounted: function() {
    this.$el.setAttribute("isVueComponent", this.$options.name);
  }
};

As long as you set the mixin to the components you need it in, when you click an element you can test the attributes to see if there's a component name in there. 只要将mixin设置为需要它的组件,单击元素时,您就可以测试属性以查看其中是否存在组件名称。

See this codepen for a fuller example: https://codepen.io/huntleth/pen/EpEWjJ 有关完整示例,请参见此Codepen: https ://codepen.io/huntleth/pen/EpEWjJ

Clicking the smaller blue square will return the component name of the component that rendered it. 单击较小的蓝色方块将返回渲染它的组件的组件名称。

EDIT - It should be noted though that this obviously would only work if the element is actually inside that components root element. 编辑-应该注意的是,这显然仅在元素实际上位于该组件根元素内部时才起作用。 I think that would be the case for almost all uses. 我认为几乎所有用途都是如此。

获得this.$parent是指组件的父代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM