Vue.js - When Property is Undefined and How to Render it in Browser

My experience with Vue has been quite puzzling. I've encountered an issue while trying to render a nested property of an object called descrizione, and although it does work, I keep receiving a warning from Vue in the console:

TypeError: Cannot read property 'descrizione' of undefined"

Let me share the code snippet that's causing this dilemma:

HTML

<div id="input-container">
  {{modello.lineaGialla.descrizione}}
  <input 
     class="styled-checkbox"
     type="checkbox"
     v-for="(servizio, index) in modello.lineaGialla.servizi" 
     v-bind:style="{left:servizio.x+'px',top:servizio.y+'px'}"
     v-model="servizio.selected"
     v-on:click="AddServizi(servizio.selected,servizio.nomeServizio)"
     />
  <br/>
  {{modello.lineaBlu.descrizione}}
  <input 
     class=""
     type="checkbox"
     v-for="(servizio, index) in modello.lineaBlu.servizi" 
     v-model="servizio.selected"
     v-on:click="AddServizi(servizio.selected,servizio.nomeServizio)"
     />
</div>

JSON

{
"lineaGialla": {
  "class":"gialla", 
  "selected": false,
  "descrizione": "Questa è linea gialla",
  "descrizione_breve":"descrizione breve gialla",
  "descrizione_lunga":"descrizione lunga gialla",
  "servizi": [
      {"nomeServizio":"servizio_giallo1","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":534,"y":83,"selected": false},
      {"nomeServizio":"servizio_giallo2","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":399,"y":259,"selected": false},
      {"nomeServizio":"servizio_giallo3","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":224,"y":262,"selected": false},
      {"nomeServizio":"servizio_giallo4","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":150,"y":502,"selected": false}
  ]
},
"lineaBlu": {
  "class":"blu",    
  "selected": false,
  "descrizione": "Questa è la linea blu",
  "descrizione_breve":"descrizione breve blu",
  "descrizione_lunga":"descrizione lunga blu",
  "servizi": [
      {"nomeServizio":"servizio_blu1","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":534,"y":83,"selected": false},
      {"nomeServizio":"servizio_blu2","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":399,"y":259,"selected": false},
      {"nomeServizio":"servizio_blu3","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":224,"y":262,"selected": false},
      {"nomeServizio":"servizio_blu4","descrizione":"qui desc <br/> breve","descrizione_lunga":"qui desc lunga","x":150,"y":502,"selected": false}
  ]
}

JS I've enlisted the help of a self-invoked function for making an ajax call:

var Callmodule = (function(){
var urljsonEntrata= "modello.json";

function getmodules(){
    var req = $.ajax({
        url: urljsonEntrata,
        dataType: 'json',
        type: 'GET'
    });

    req.done(function(data){
        console.log('ajax to '+urljsonEntrata+' DONE');
        console.log(data);
        console.log('-----------------------------');
    });

    req.fail(function( jqXHR, textStatus, errorThrown ) {
        console.log('ajax to '+urljsonEntrata+' FAIL');
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
        console.log('-----------------------------');
    });
    return req;
}
return {
    callGetmodules : getmodules(),
}
})();



var modello = {};

var VueApp = (function(){

 //VUE JS
var Metromappa = new Vue({
 el: '#metromappa',
  data: {
    modello:modello
  },
  methods:{
    getModuleData : function(){             
       var req = Callmodule.callGetmodules;
       var self = this;
       req.done(function(data){
         self.modello=data;
       });
       req.fail(function(jqXHR,textStatus,errorThrown){
        console.log('richiesta andata a male')
       });  
   }  

This whole situation is truly befuddling.

Answer №1

The issue at hand arises from the fact that you are fetching your data in an asynchronous manner while your template expects the data to be immediately available.

For instance, within your template, you have the following snippet of code:

modello.lineaGialla.descrizione

However, during the initial rendering of the template, the value of lineaGialla either does not yet exist or is simply undefined. Consequently, when attempting to access the property descrizione, which belongs to the undefined value, it results in an error being thrown.

To resolve this issue, refrain from rendering the template until the necessary data is available,

<div  v-if="modello.lineaGialla && modello.lineaBlu" id="input-container">

or handle the access more cautiously like so:

{{modello.lineaGialla && modello.lineaGialla.descrizione}}

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

Changing a CURL request to an AJAX request

Could someone help me convert the CURL request below into HTML? Unfortunately, the application does not provide any AJAX documentation on their website. curl -X GET --header "Accept: application/json" --header "user-key: xxxx" "https://developers.abcdef ...

Problem with detecting collisions in Three.js

Currently, I am developing a simple game where players can add objects (cubes) to the scene at the position of a raycaster (mouse) click on a large ground plane. To prevent cubes from overlapping with each other, I have implemented basic collision detectio ...

problem with displaying sidebar in Ember template

Using Ember, I have a login page where I don't want to display the header or sidebar navigation for my site until the user is authenticated. Once they are logged in, I want the header and sidebar to be visible. Currently, I am achieving this by checki ...

What are the steps for incorporating a YouTube playlist into a website?

I'm in the process of creating a website and I'd like to incorporate a YouTube video playlist that looks similar to this example - http://www.youtube.com/user/icicibank/home. I plan to use HTML5, JavaScript, and the YouTube API. Can you provide g ...

Issue with data sorting in Laravel backend not reflecting properly in Vue frontend

Issue at hand: When fetching and displaying rows from a database using Laravel controller and Vue, the sorting order seems to be affected. Even though Laravel properly sorts the results from the model by name, once fetched through Vue and displayed in an ...

How can I make <p> elements change color when scrolling?

My Goal https://i.sstatic.net/JbdXR.gif I aim to bring attention to the <p> element as the user scrolls on the page. Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down. My Attempt window.o ...

Discover unique values for a specified JSON attribute among all records in a database

Is it possible to fetch all the unique values of a json-property from multiple documents in a collection using the Marklogic Java Client API? For example, if there are 3 "MyDocument" type documents with the property "myProperty" as follows: MyDocument1.j ...

The specified message formats required for the operation include 'XML' and 'JSON'

Creating a WCF REST service includes defining methods for adding, deleting, and editing news entities. Here is an example of such a service: [ServiceContract] public interface INewsRepository { [OperationContract] [WebInvoke(Me ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...

Creating a texture from an iframe in three.js

Is it possible to dynamically assign an iFrame as a texture onto an obj model? I know that it can be done with videos. I found this example interesting - where an iFrame is loaded into a three.js environment: And also this example, which demonstrates map ...

How to access and extract data from nested dictionaries in JSON format

I have a lengthy JSON file that begins with {"requestId": "2", "records": { "totalRecords": 5, "currentPageSize": 5, "currentPageNumber": 1 ... I uploaded the file and stored it in a variable usin ...

What is the best way to include an icon in a Vue child component?

Struggling to implement the image in the template using both the img tag and as a background. Despite having the correct path to the icon, neither method seems to work. Check out the code snippet here <div> <a href="#" class="icon" > ...

JavaScript - changing object into a string (not functioning properly)

Looking to convert a JavaScript object into a string? Here's an example: var obj = {"name": "XXX", "age": "27"}; After doing some research, I found out about JSON.stringify(obj); JSON.stringify(obj); works perfectly when the IE8 modes are set as fo ...

What is the best way to manage an unused parameter received from an API in a Flutter

In order to avoid Gson errors when parsing objects, I only need the name and id parameters for Dropdown. How can I handle unwanted parameters from the API response in a Flutter object? import 'package:meta/meta.dart'; import 'dart:conve ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...

Retrieve data from JSON objects, particularly within a Ruby on Rails framework

"divisions":{ "ocd-division/country:us/state:co/place:aurora":{ "name":"Aurora city", "scope":"citywide", "officeIds":[ "O0", "O1"] }} Utilizing the Google Civic Information API to retrieve representative ...

How can I deactivate the main color of the FormLabel when the focus is on the radio button group?

Is there a way to change the color of FormLabel to black instead of the primary color when the radio button group is focused? https://i.sstatic.net/h3hML.png const styles = { formLabel: { color: "#000" }, formLabelFocused: { color: "#000" ...

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...