Code Tree Code Tree - 3 days ago 5
Javascript Question

vuejs Can't access refs from component

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 undefinded.

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.

Thanks.

here is console log

Answer

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 event

mounted: function() {
    console.log(this.$refs.icanvas);
},
Comments