VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component:

...
<v-stepper-step
:rules="[()=>isValid(1)]"
>
    MyStep
</v-stepper-step>
<v-stepper-content>
    <Mytag ref="MyReference" />
</v-stepper-content>
...
methods: {
    isValid(number){
      return mySwitch(number)
 }
    mySwitch(number){
      let v = false
      switch(number){
        case '1':
        v = this.$refs.MyReference.$refs.MyTagForm.validate()
        break
      }
     return v
 }
}

Child Component:

...
<v-form
  ref="MyTagForm"
>
...
</v-form>
...

Encountering an issue: upon initial page load, a TypeError is thrown "Cannot read properties of undefined (reading '$refs')". However, once the page loads and I change between steps, the validation works correctly.

I suspect that the reference does not exist at the start. I attempted to use setInterval and setTimeout around the isValid and mySwitch methods, but then the validation consistently returns false.

Seeking assistance from anyone who can provide insight on this matter.

Answer №1

The issue lies in the rendering process of components in Vue.js, where a component goes through various stages such as creation before mounting. As a result, you are trying to access a DOM object that has not yet been rendered by the framework. Essentially, you are attempting to retrieve something that does not currently exist.

To resolve this issue, it is important to consider that the child component may not have been rendered and to delay validation until after the component has been mounted. One approach is to have the child component notify the parent once it has successfully mounted, returning a default validation value of either true or

false> until then. The following example demonstrates this concept:</p>
<pre><code>...
<v-stepper-step
:rules="[()=>isValid(1)]"
>
    MyStep
</v-stepper-step>
<v-stepper-content>
    <Mytag ref="MyReference" v-on:ready="childReady = true" />
</v-stepper-content>

{
  ...
  data() {
    return {
      childReady: false
    }
  },
  methods: {
    isValid(number){
      return mySwitch(number)
  }
  mySwitch(number){
    if(!this.childReady) {
      return false;
    }

    let v = false
    switch(number){
      case '1':
      v = this.$refs.MyReference.$refs.MyTagForm.validate()
      break
    }
    return v
  }
}
...
<v-form
  ref="MyTagForm"
>
...
</v-form>
...

{
  ...
  mounted() {
    this.$emit('ready');
  }
}

There are alternative approaches to handling this situation, and there are likely more effective solutions than the one provided above. Nevertheless, I hope this explanation helps you understand the root cause of the problem and guides you towards crafting a better solution for your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript issue causing unexpected behavior in top and left positions

I've been experiencing an issue with my JavaScript code on an HTML file. Despite changing the top or left values, the image does not move as expected. I've spent hours searching for a solution and even tried copying tons of different code snippet ...

Ways to eliminate existing information when conducting a search

Recently, I was tasked with integrating a search engine into a website that already has a list of data displayed on the first page. The challenge I faced was figuring out how to hide or remove this existing data when a new search request is made. You can v ...

I have a collection of emails stored as a string that I would like to convert into a json or javascript object and store in a mongodb

After selecting multiple user emails, I receive the following data: "participants" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294b5b404847695d41405b4d5b465c5d4c074a4644">[email protected]</a>,<a href="/ ...

How to select a DOM element in Angular 2.x

Although it may seem simple, there are not many examples of using Angular 2.0 yet. In one of my components, I have a situation where I need to add a class to the body tag. However, my application is bootstrapped deeper than the body element, so I am looki ...

Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows: <div> <span>Liza</span>, <span>Eric</span>, <span>Mic ...

Steps to upload an image directly into a Vue component?

I'm having trouble adding a photo to my project locally. Can someone provide guidance on how to accomplish this? template: <li v-for="book in books" :key="book.id"> *Some code here* <img :src=" ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

What is the best way to modify the text color within a Navbar, especially when the Navbar is displayed within a separate component?

First question on StackOverflow. I have a Next App and the Navbar is being imported in the _app.js file. import Navbar from "../Components/Navbar"; function MyApp({ Component, pageProps }) { return ( <> <Navbar /> ...

JavaScript For Each loops are really starting to frustrate me

My issue seems to be straightforward. I am attempting to update a list of objects called localData with another list of objects that I received after making an AJAX request (referred to as data). The process involves using two loops, however, when I atte ...

Attempting to store the output of a function in a variable

My current script is designed to verify if the value of a selected element matches the span id. While the function itself functions correctly (verifying object.id via alert), I am encountering issues with variable assignment. When attempting to alert the ...

Refresh KendoUI Grid data with latest additions

I currently possess: $.post('buying-grid/split/' + config.route.params.id, item).success(function(data){ var ds = new kendo.data.DataSource(); ds.data(data) $('#buyingGrid').data('ke ...

What is the best way to monitor a dynamic variable in vuex?

On a side panel component, there is an input that is conditionally displayed when a node is selected in a graph. This input corresponds to the name of the selected node and is part of the side panel component. The graph itself is housed within its own comp ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

Can anyone provide a method for obtaining a date that is x days earlier through date arithmetic?

Is there a method to obtain the date from 63 days ago with only day, month, and year information needed, excluding hours, minutes, and seconds? I am aware that one can calculate Date object - Date object, but I am curious if it is feasible to derive a dat ...

Is it possible to utilize Vue 3's watch feature with primitive data types?

When I retrieve data, I want to toggle a boolean value to display the <Loading /> component. I prefer not to base my condition on array length. Therefore, I have opted for this approach. However, the <Loading /> component does not respond to ch ...

Changing the z-index using createjs

Is there a way to ensure that the dragged item always stays on top when moved? How can I prevent it from getting dragged underneath another object? Can I specify which "sequenceNumbers" should be moved to the top of the sorting order? //++++++++ ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...

Encountering issues with verifying login credentials in Angular 2

Greetings! I have designed a login page where the user will be logged in if the response is successful, otherwise an error message will be displayed. Below is the JSON data with email and password fields: { Email": "<a href="/cdn-cgi/l/email-protect ...

The calculation of Value Added Tax does not involve the use of jQuery

My form setup is as follows: <form method="post" action="" id="form-show"> <table class="table table-bordered table-striped table-hover" id='total' style="width:100%;"> ...

Tips for preventing multiple clicks when posting AJAX requests in jQuery

Using Django, I was able to create a website and implement a voting page with jQuery AJAX. The code works perfectly fine as shown below: <!doctype html> <html> <head> <script src="jquery-1.10.2.min.js"></script> <met ...