Javascript DOM 元素对应的 vue.js 组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26915193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DOM element to corresponding vue.js component
提问by Ghigo
How can I find the vue.js component corresponding to a DOM element?
如何找到一个 DOM 元素对应的 vue.js 组件?
If I have
如果我有
element = document.getElementById(id);
element = document.getElementById(id);
Is there a vue method equivalent to the jQuery
$(element)?
是否有与 jQuery 等效的 vue 方法
$(element)?
采纳答案by blockhead
The proper way to do with would be to use the v-eldirective to give it a reference. Then you can do this.$$[reference].
正确的处理方法是使用v-el指令给它一个引用。那你就可以了this.$$[reference]。
Update for vue 2
更新 vue 2
In Vue 2 refs are used for both elements and components: http://vuejs.org/guide/migration.html#v-el-and-v-ref-replaced
在 Vue 2 中,refs 用于元素和组件:http: //vuejs.org/guide/migration.html#v-el-and-v-ref-replaced
回答by Kamil Kie?czewski
Just by this (in your method in "methods"):
就这样(在“方法”中的方法中):
element = this.$el;
:)
:)
回答by acdcjunior
In Vue.js 2 Inside a Vue Instance orComponent:
在 Vue.js 2 中的 Vue 实例或组件中:
- Use
this.$elto get the HTMLElement the instance/component was mounted to
- 使用
this.$el来获取HTML元素的实例/组件被安装到
From an HTMLElement:
来自HTMLElement:
- Use
.__vue__from the HTMLElement- E.g.
var vueInstance = document.getElementById('app').__vue__;
- E.g.
.__vue__从 HTMLElement 使用- 例如
var vueInstance = document.getElementById('app').__vue__;
- 例如
Having a VNodein a variable called vnodeyou can:
在VNode变量中调用 avnode可以:
- use
vnode.elmto get the element that VNode was rendered to - use
vnode.contextto get the Vue instance that VNode belogs to - use
vnode.componentInstanceto get the Componentinstance that VNode is about
- 用于
vnode.elm获取 VNode 渲染到的元素 - 用于
vnode.context获取 VNode 所属的 Vue 实例 - 用于
vnode.componentInstance获取VNode 所在的Component实例
Source, literally: vue/flow/vnode.js.
来源,字面意思是:vue/flow/vnode.js。
Runnable Demo:
可运行的演示:
Vue.component('my-component', {
template: `<input>`,
mounted: function() {
console.log('[my-component] is mounted at element:', this.$el);
}
});
Vue.directive('customdirective', {
bind: function (el, binding, vnode) {
console.log('My Element is:', vnode.elm);
console.log('My componentInstance is:', vnode.componentInstance);
console.log('My Vue Instance is:', vnode.context);
}
})
new Vue({
el: '#app',
mounted: function() {
console.log('This Vue instance is mounted at element:', this.$el);
console.log('From the element to the Vue instance:', document.getElementById('app').__vue__);
console.log('Vue component instance of my-component:', document.querySelector('input').__vue__);
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<h1>Open the browser's console</h1>
<div id="app">
<my-component v-customdirective=""></my-component>
</div>
回答by BigBlueHat
If you're starting with a DOM element, check for a __vue__property on that element. Any Vue View Models (components, VMs created by v-repeatusage) will have this property.
如果您从 DOM 元素开始,请检查__vue__该元素的属性。任何 Vue 视图模型(组件、v-repeat使用创建的 VM )都将具有此属性。
You can use the "Inspect Element" feature in your browsers developer console (at least in Firefox and Chrome) to view the DOM properties.
您可以使用浏览器开发人员控制台中的“检查元素”功能(至少在 Firefox 和 Chrome 中)来查看 DOM 属性。
Hope that helps!
希望有帮助!
回答by Kathan Shah
Since v-ref is no longer a directive, but a special attribute, it can also be dynamically defined. This is especially useful in combination with v-for.
由于 v-ref 不再是一个指令,而是一个特殊的属性,它也可以动态定义。这在与 v-for 结合使用时特别有用。
For example:
例如:
<ul>
<li v-for="(item, key) in items" v-on:click="play(item,$event)">
<a v-bind:ref="'key' + item.id" v-bind:href="item.url">
<!-- content -->
</a>
</li>
</ul>
and in Vue component you can use
在 Vue 组件中你可以使用
var recordingModel = new Vue({
el:'#rec-container',
data:{
items:[]
},
methods:{
play:function(key,e){
// it contains the bound reference
console.log(this.$refs['item'+key]);
}
}
});
回答by Yauheni Prakopchyk
So I figured $0.__vue__doesn't work very well with HOCs (high order components).
所以我认为$0.__vue__HOC(高阶组件)不能很好地工作。
// ListItem.vue
<template>
<vm-product-item/>
<template>
From the template above, if you have ListItemcomponent, that has ProductItemas it's root, and you try $0.__vue__in console the result unexpectedly would be the ListIteminstance.
从上面的模板中,如果您有ListItem组件,ProductItem它是根,并且您$0.__vue__在控制台中尝试,结果意外地将是ListItem实例。
Here I got a solution to select the lowest level component (ProductItemin this case).
在这里,我得到了一个选择最低级别组件的解决方案(ProductItem在本例中)。
Plugin
插入
// DomNodeToComponent.js
export default {
install: (Vue, options) => {
Vue.mixin({
mounted () {
this.$el.__vueComponent__ = this
},
})
},
}
Install
安装
import DomNodeToComponent from'./plugins/DomNodeToComponent/DomNodeToComponent'
Vue.use(DomNodeToComponent)
Use
用
- In browser console click on dom element.
- Type
$0.__vueComponent__. - Do whatever you want with component. Access data. Do changes. Run exposed methods from e2e.
- 在浏览器控制台中单击 dom 元素。
- 键入
$0.__vueComponent__。 - 用组件做任何你想做的事。访问数据。做改变。从 e2e 运行公开的方法。
Bonus feature
奖金功能
If you want more, you can just use $0.__vue__.$parent. Meaning if 3 components share the same dom node, you'll have to write $0.__vue__.$parent.$parentto get the main component. This approach is less laconic, but gives better control.
如果你想要更多,你可以使用$0.__vue__.$parent. 这意味着如果 3 个组件共享同一个 dom 节点,则您必须编写$0.__vue__.$parent.$parent以获取主要组件。这种方法不那么简洁,但提供了更好的控制。
回答by Jossef Harush
this.$el- points to the root element of the componentthis.$refs.<ref name>+<div ref="<ref name>" ...- points to nested element
this.$el- 指向组件的根元素this.$refs.<ref name>+<div ref="<ref name>" ...- 指向嵌套元素
use
$el/$refsonly aftermounted()step of vue lifecycle
仅在vue 生命周期的步骤之后使用
$el/$refsmounted()
<template>
<div>
root element
<div ref="childElement">child element</div>
</div>
</template>
<script>
export default {
mounted() {
let rootElement = this.$el;
let childElement = this.$refs.childElement;
console.log(rootElement);
console.log(childElement);
}
}
</script>
<style scoped>
</style>
回答by bernie
回答by candleHyman
If you want listen an event (i.e OnClick) on an input with "demo" id, you can use:
如果您想在带有“演示”ID 的输入上监听事件(即 OnClick),您可以使用:
new Vue({
el: '#demo',
data: {
n: 0
},
methods: {
onClick: function (e) {
console.log(e.target.tagName) // "A"
console.log(e.targetVM === this) // true
}
}
})
回答by anonymous
Exactly what Kamil said,
正如卡米尔所说,
element = this.$el
But make sure you don't have fragment instances.
但请确保您没有片段实例。


