Utilize the v-if directive with nested object properties for dynamic conditional rendering

I need to verify if the item object has a property called 'url' set. If it's not present, I would like to display a placeholder image. Here is an example of what I want to achieve:

        <img
          v-if="item.relationships.main_image.attributes.url"
          :src="item.relationships.main_image.attributes.url"
          :alt="item.attributes.name"
          class="h-full w-full"
        />
        <img v-else :src="require('@/assets/placeholder.png')" alt=""/>

The issue lies in the fact that my item object might not have any properties since the backend only sends those properties if there is actually an image associated with the item.

Is there a way to determine if an object possesses that deeply nested property?

Error encountered: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'attributes')

Answer №1

To make this code more efficient, you can simplify it by removing the extra img tag. Additionally, if any properties of the item object may be null, you can utilize optional chaining (for example, item?.relationships...).

Since we are unsure about which properties may or may not be null, let's consider the worst-case scenario:

<img :src="item?.relationships?.main_image?.attributes?.url || require('@/assets/placeholder.png')"
     :alt="item?.attributes?.name || 'placeholder'"
     class="h-full w-full"/>

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

Altering the hue of a picture

Looking to alter the color of an image on a webpage, specifically a carport. It's crucial that the texture and shadows remain consistent. Swapping out images with different colors would require an excessive amount of images, so I'm seeking advice ...

Koa and Stripe are patiently holding off on displaying the page

My current setup involves using koa and stripe for processing a one-time payment. Although the functionality is there, I'm facing an issue where the page renders before the 'data' assignment takes place. This results in the 'id' sh ...

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

Certain images are not being retrieved by Express on Linux, although they are functioning properly on Windows

When using a template to display HTML code, everything works smoothly on Windows. However, when transferring the code to a Linux machine, an issue arises - "Cannot GET /SmallVacImages/1.jpg". It seems that the index.html file can load images from the publi ...

The error message "ch.match is not a function" appeared in the Javascript code

Here are two functions that I need help with: //Function A var ltrToNato = function(ch) { var x = ch; var nato = ('{"A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", "G": "Golf", "H": "Hotel", "I": "India" ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

How come my keyframes animation isn't functioning properly on my div element?

I am currently designing a custom animation for a checkers game. My goal is to create an effect where the checker piece moves slowly to its next spot on the board. Below is the CSS code I have used: @keyframes animateCheckerPiece { 0% {top: ...

Is the Jest function, containing an asynchronous call to User.findAll [using Sequelize with PostgreSQL], failing its test?

Why is my test failing for the getAllUsers function? I suspect that the assertions are executed before all async calls to User.findAll complete. Any suggestions on how to fix this? Here is the code being tested: const { Op } = require('sequelize&apo ...

Error encountered when importing components in VueJS due to module not found

Currently, I am facing an issue with my app where I'm loading components using <router-view/>. The specific problem arises when importing the components in router.js, as it consistently gives me this error: These relative modules were not foun ...

Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result. <template> <select v-model="tutor_work.start_year"> <option>{{tutor_work.start_year}}< ...

Ramjet: Unveiling the Magic of Making Elements Appear and Disappear

Currently, I am attempting to implement the code for ramjet from . However, I am facing an issue where element a does not disappear when transitioning into b. Additionally, I am encountering an error message "--Uncaught TypeError: Cannot read property &apo ...

Issue with Node.js OAuth authentication

As someone new to Node.js and specifically OAuth, I have been exploring the use of Google APIs with Node.js. So far, here is what I've accomplished: var fs = require('fs'); var readline = require('readline'); var google = require( ...

Automated pagination integrated with automatic refreshing of div every few seconds

I am currently working on setting up a datatable and I need it to be displayed on the monitor in such a way that it can refresh the div and automatically paginate to the next page. However, whenever the div is refreshed, the auto-pagination gets cancelle ...

How to eliminate the initial class with jQuery

I am encountering some issues with removing a class using jQuery. When I open a modal in Bootstrap, it generates code like this: <div class="modal-backdrop fade in"> in the footer. However, when I open a modal within another modal (2 modals), ther ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

When iterating through a JavaScript object, opt for utilizing references instead of repeatedly specifying the path

for (var element in array[index1][index2][index3].property) { alert(array[index1][index2][index3].property[element].data); } Is there a more succinct way to achieve the same result by referencing the object directly like this: for (var ...

Is there a way for me to display the output from Firebase on the html template when the page first loads?

I am currently in the process of building a blog post page using VueJs. Here is my template: <template> ... <q-item-section> <q-item-label class="text-subtitle1"> <strong>Danny Co ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...