DOM element to corresponding vue.js component
The proper way to do with would be to use the v-el
directive to give it a reference. Then you can do this.$$[reference]
.
Update for 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
In Vue.js 2 Inside a Vue Instance or Component:
- Use
this.$el
to get the HTMLElement the instance/component was mounted to
From an HTMLElement
:
- Use
.__vue__
from the HTMLElement- E.g.
var vueInstance = document.getElementById('app').__vue__;
- E.g.
Having a VNode
in a variable called vnode
you can:
- use
vnode.elm
to get the element that VNode was rendered to - use
vnode.context
to get the VueComponent instance that VNode's component was declared (this usually returns the parent component, but may surprise you when using slots. - use
vnode.componentInstance
to get the Actual VueComponent instance that VNode is about
Source, literally: vue/flow/vnode.js.
Runnable Demo:
Vue.config.productionTip = false; // disable developer version warningconsole.log('-------------------')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('[DIRECTIVE] My Element is:', vnode.elm); console.log('[DIRECTIVE] My componentInstance is:', vnode.componentInstance); console.log('[DIRECTIVE] My context is:', vnode.context); // some properties, such as $el, may take an extra tick to be set, thus you need to... Vue.nextTick(() => console.log('[DIRECTIVE][AFTER TICK] My context is:', vnode.context.$el)) }})new Vue({ el: '#app', mounted: function() { console.log('[ROOT] This Vue instance is mounted at element:', this.$el); console.log('[ROOT] From the element to the Vue instance:', document.getElementById('app').__vue__); console.log('[ROOT] Vue component instance of my-component:', document.querySelector('input').__vue__); }})
<script src="https://unpkg.com/vue@2.5.15/dist/vue.min.js"></script><h1>Open the browser's console</h1><div id="app"> <my-component v-customdirective=""></my-component></div>