Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

HTML

<div id="app>   <template id="image-capture">     <div class="row" >       <canvas ref="icanvas" ></canvas>     </div>   </template> </div>  

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.

here is console log

like image 320
Code Tree Avatar asked Nov 30 '16 09:11

Code Tree


People also ask

How do I access Vue refs?

Accessing the Refs Note that you can only access the ref after the component is mounted. If you try to access $refs. input in a template expression, it will be null on the first render. This is because the element doesn't exist until after the first render!

Why is ref undefined Vue?

It is because the input property itself is undefined, so we can't get access to the value property. That is because of the previous error happens during component rendering. So the computed value will be undefined as well.

What is Vue REF ()?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.

Are refs reactive Vue?

$refs...are not reactive. However, I have used such refs in templates and they are indeed reactive, and even in methods, computed props, and watchers (as long as you access it after being mounted). Several third party vue libraries e.g. this one also provides features that use/depend on the reactivity of refs.


2 Answers

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); }, 
like image 114
Mihai Vilcu Avatar answered Nov 13 '22 07:11

Mihai Vilcu


You can use $nextTick() function, code inside $nextTick() will run after DOM update.

this.$nextTick(function () {      console.log(this.$refs.ANY_COMPONENT_REF)  }) 
like image 38
Kishan Madhesiya Avatar answered Nov 13 '22 08:11

Kishan Madhesiya