I have an element with a ref
that is defined and ends up getting rendered into the page :
<div ref="russian" ...> ... </div>
I want to access the DOM element properties like offset...
or something. However, I keep getting undefined
and I haven't the faintest idea why. After some searching it's clear that refs
are only applicable to one file but I'm not using this anywhere besides this one page. I'm saying this to log it:
console.log('REFS', this.refs.russian);
What could be causing this?
If we try to access the current property of the ref directly in the component, we would get undefined back because the ref hasn't been set up and the div element has not been rendered. You can also access the current property of the ref in an event handler function. Copied!
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.
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!
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.
Check that you are not accessing ref before the child component has been mounted. E.g. it doesn't work in componentWillMount
. A different pattern which auto invokes ref related callback after the element has been mounted is this-
<div ref={(elem)=>(console.log(elem))}/>
You can use this notation to get mounted elements in deep nesting as well -
<div ref={this.props.onMounted}/>
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