I am trying to get the canvas element which is inside a template of a component, found great documentations for vuejs1 but not for vuejs2 where "ref" is the only way to get the element. I am getting the object though, but when I try to access the variable it is undefined.
My html
<div id="app>
<template id="image-capture">
<div class="row" >
<canvas ref="icanvas" ></canvas>
</div>
</template>
</div>
My js
const ic = {
template: '#image-capture' ,
created () {
console.log(this.$refs); //this returns object
console.log(this.$refs.icanvas); // but this is undefined
}
}
const routes = [
{ path: '/ic', component: ic},
]
const router = new VueRouter({
routes
})
new Vue({
router,
}).$mount('#app')
I need to get the icanvas element.
Normally, you can access the ref in
mounted
, just like @Mihai Vilcu posted:However, as @BrownBe said,
Until 2018.10.27, it is still a question, and here is the latest issues.
The reason can be found here:
And here is what I do to solve this question:
And here is the
$_xsl__watchRefs
You can alter it as you need. Here is MutationObserver which supported IE11+.
Another easy choice. Suppose you use
v-for
like:And
In this case, you can try:
In some cases, both methods won't work because
this.$refs.lazyImages
has already existed. So, the safest method is:The
created
is fired before the template is processed.You can find more details here: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
You should be able to access the $refs on the
mounted
eventi had the exact same issue, in my case i solved it by accessing the ref in the method that changes the v-if with nextTick.
You can use $nextTick() function, code inside $nextTick() will run after DOM update.