Question

Vue.js refs are undefined, even though this.$refs shows theyre there

I have a reference to a component

<Gmap ref="mapRef">

In mounted I am doing this, to see the objects are available

mounted(){
    let self = this
    console.log(self.$refs) // Shows the mapRef object reference
    console.log(self.$refs.mapRef) // returns undefined ???
}

self.$refs shows...

  mapRef: VueComponent {_uid: 207, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}

So then why does self.$refs.mapRef return undefined?? Even though it's clearly there??

 48  100459  48
1 Jan 1970

Solution

 57

I solved this by using v-show instead of v-if.

I had the component inside a v-if statement.

 <div v-if="!isLoading"> 
   <GMap ref="mapRef" />
 </div>

I just changed that to v-show

<div v-show="!isLoading"> 
   <GMap ref="mapRef" />
 </div>

And now the object is available in mounted(). Still find it strange that the console.log(this.$refs) showed it being available as a key on this.$refs, even though it actually wasn't? Thats strange behaviour.

The other wierd thing was, that even if I tried to access this.$refs.mapRef in my data loading section, AFTER THE DATA WAS LOADED, (ie after isLoading=false), I still couldn't access it. Even though then, it should've been available because the v-if passed.

So v-show solved it, by just hiding the div, instead of not rendereding it. Stupid little workaround.

2019-01-24

Solution

 22

I had a similar problem getting a ref to a leaflet map instance, try waiting for the "nextTick"

mounted(){
  this.$nextTick(()=>{
    let self = this
    console.log(self.$refs) // Shows the mapRef object reference
    console.log(self.$refs.mapRef) // returns undefined ???
  });
}

see the docs for more- https://v2.vuejs.org/v2/api/#vm-nextTick and https://v2.vuejs.org/v2/api/#mounted

2019-01-24