Vue this.$refs is undefined during mounted() in vue2-dropzone component

1.2k views Asked by At

I am currently trying to make sure the my componentvue2dropzone is disabled on the initial load of the application, then i began to notice this error in the console when I am trying to make the app mobile responsive.

[Vue warn]: Error in mounted hook: "TypeError: this.$refs.vue2dropzone is undefined"

followed by a

TypeError: "this.$refs.vue2dropzone is undefined"

I have a noticed this problem occurring in Vue that seems to be a common issue based on my research, such that when you have v-if or v-else-if in a component child modifying to show something, the lifecycle will be called again.

A snippet of my code for vue2dropzone component just includes

In my typescript file

private mounted() {
  this.$refs.vue2dropzone.disable(); 
}

In my vue file

    <div v-if="some condition">
     <form>
       <vue2Dropzone 
       ref="vue2dropzone" 
       id="dropzone" 
       class="vue-dropzone"
       ></vue2Dropzone> 
     </form>
    </div>
    <div v-else-if="some other condition">
     <form>
       <vue2Dropzone 
       ref="vue2dropzone" 
       id="dropzone" 
       class="vue-dropzone"
       ></vue2Dropzone> 
     </form>
   </div>

I am beginning to wonder if the v-show being before the first v-if doesn't let recall the lifecycle because when I am on the web app, it is disabled but when i switch to mobile responsiveness it shows up as undefined.

Are there any solutions to solve this? I have seen v-show being used and this.$nextTick but it really didn't help me in my case. Should i put this in another part of the lifecycle besides mounted()?

1

There are 1 answers

0
penguin On BEST ANSWER

ok so I have found a method to resolve this. It seems as the vue app is loading it is quite possible that since the v-if is there the condition is not fulfilled until other asynchronous processes have fully loaded which more than likely has past the mounted lifecycle.

In order to solve this we can use a native feature of vue2-dropzone which is vdropzone-mounted so whenever it is being toggled or loads, the function runs.

e.g.

Create a function for using the disable function of vue2-dropzone

public disableDropZoneBox() {    
  this.$refs.vue2dropzone.disable();
}

in vue file

 <vue2Dropzone 
 ref="vue2dropzone" 
 id="dropzone" 
 class="vue-dropzone"
 @vdropzone-mounted="disableDropZoneBox"
 ></vue2Dropzone>