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.
<div id="app> <template id="image-capture"> <div class="row" > <canvas ref="icanvas" ></canvas> </div> </template> </div>
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.
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!
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.
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.
$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.
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); },
You can use $nextTick() function, code inside $nextTick() will run after DOM update.
this.$nextTick(function () { console.log(this.$refs.ANY_COMPONENT_REF) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With