can not access parentElement within custom directive's bind function
See original GitHub issueI have following simple code:
define a test-comp component; define a custom directive log-something within that component’s template, i use a custom directive v-log-something; within the diretive’s bind function**, i want to log out the belonging element’s parentElement; Unfortunately, the null result is returned.** Note: It works if I put the v-log-something diretive in a normal html tag( Not within the component’s template). I am not sure whether or not this is a bug. I guess it is caused by some lifecycle issue: When diretive’s bind function is called, the belonging component has not been inserted into dom. When can we make sure everything is in dom and we can access parentElement node within the directive’s bind function safely?? here is the fiddle: http://jsbin.com/wajarad/edit?html,js,console,output
<body id="body">
<test-comp></test-comp>
</body>
Vue.component('test-comp',{
template: '<div v-log-something>this comes from test-comp</div>'
});
Vue.directive('log-something',function(){
console.log(this.el.parentElement);
});
new Vue({
el: '#body'
});
Issue Analytics
- State:
- Created 7 years ago
- Comments:12 (3 by maintainers)
Top GitHub Comments
I faced this issue in Vue 2.5.13. Here is workaround works for me:
@nat1597 in Vue 2 directives changed a lot. Hook signatures are now different and no more
this
.You can access the vm as
vnode.context
, withvnode
being the third argument to the hook. And the old workaround withnextTick
is still needed if you want to access vm from the directive’sbind
.