Adjusting the empty image source in Vue.js that was generated dynamically

Currently experimenting with Vue.js and integrating a 3rd party API. Successfully fetched the JSON data and displayed it on my html, but encountering issues with missing images. As some images are absent from the JSON file, I've saved them locally on my laptop.

Attempted to set empty image sources using v-if in my html without success (refer to the comments in my html file).

Additionally, tried assigning a class for each img element and then setting the src attribute using jQuery $("#zTTWa2").attr("src", "missing_beers-logo/11.5%20plato.png"); also without any luck.

Where am I going wrong? It's possible that my approach is flawed due to my limited coding experience, so any suggestions would be greatly appreciated. Thank you in advance.

var app = new Vue({
  el: "#app",
  data: {

    beers: [],
    decrArray: [], //array with img links
    cleanedArray: [], //without undefined
    path: 0,
    images: [missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png",
    "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png",
"missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png", "missing_beers-logo/11.5%20plato.png"],
  created: function() {
    this.getData();
  },

  methods: {
    getData: function() {
      var fetchConfig =
        fetch("http://api.brewerydb.com/v2/beers?key=6a3ac324d48edac474417bab5926b70b&format=json", {
          method: "GET",
          dataType: 'jsonp',
          //                     responseType:'application/json',
          // "Content-Type": 'application/json',


          headers: new Headers({
            "X-API-Key": '6a3ac324d48edac474417bab5926b70b',
            'Content-Type': 'application/json',
            "Access-Control-Allow-Credentials": true,
            "Access-Control-Allow-Origin": '*',
            "Access-Control-Allow-Methods": 'GET',
            "Access-Control-Allow-Headers": 'application/json',



          })
        }).then(function(response) {
          if (response.ok) {
            return response.json();
          }
        }).then(function(json) {
          console.log("My json", json)
          //                    console.log("hi");
          app.beers = json.data;
          console.log(app.beers);
          app.pushDescr();
          console.log(app.decrArray);
          app.removeUndef();
          //console.log(app.cleanedArray);
        })
        .catch(function(error) {
          console.log(error);
        })
    },

    pushDescr: function() {
      console.log("hi");
      for (var i = 0; i < app.beers.length; i++) {
        app.decrArray.push(app.beers[i].labels);
      }


      return app.decrArray;
    },

    removeUndef: function() {
      for (var i = 0; i < app.decrArray.length; i++) {
        if (app.decrArray[i] === undefined) {
          app.decrArray[i] = "";
        }
      }
      console.log(app.decrArray);
    },
     getMissingImg(index){

   return(this.images[index]);
  },





  }
})
  <div class="app">
    <div v-for="(value, index) in beers">
      {{value.name}}
      <!--
                  
   <img  v-bind:src="decrArray[index].medium" :class="value.id"/>                 
-->
      <div v-if="decrArray[index].medium !==undefined  ">
        <img :src="decrArray[index].medium" />
      </div>
      <div v-else>
        <img :src="getMissingImg(index)" />
      </div>

    </div>



  </div>

Answer №1

When working with webpack, local images are treated as modules and should be required or imported like so:

<img :src="localImg" />

In your data object, make sure to include:

data(){
       return{
          localImg:require("missing_beers-logo/11.5%20plato.png"),
          ...
          }
       }

Alternatively, you can also do:

import img from "missing_beers-logo/11.5%20plato.png"
 export default{

  data(){
       return{
          localImg:img,
          ...
          }
       }

If you have an array of images, it's recommended to use a method like this:

<div v-else>
    <img :src="getMissingImg(index)" />
  </div>

Data:

images: ["missing_beers-logo/420%20fest.jpg","missing_beers-logo/15th%20aniversarry.png","missing_beers-logo/15th%20aniversarry.png","missing_beers-logo/3%20Weight%20beer%20.png"] 

Your method will look something like this:

   getMissingImg(index){

       return require(this.images[index]);
      }

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

Integrating a title field into every p-column with ng-template

I am exploring ng-templates for the first time. I have managed to customize each column to display names accurately, but I am encountering an issue. I would like to incorporate a title field in order to show a tooltip with the full name when hovering over ...

Watch for event triggered after completion of input field with ng-modal

One of my challenges involves implementing a text input field that prompts users to enter their name: <input type="text" ng-modal="form.name" placeholder="Enter NAME"> I've also set up a watch function to monitor changes in the form's nam ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Container element refusing to grow in size while the footer remains fixed on the screen

Description: I recently encountered an issue with the layout of my website. I have a main content div (#main) and a container div (.display), which should expand automatically with content to push the footer down. Initially, I struggled to get this workin ...

The driver instance that has forked will never cease

Issues arise when attempting to run multiple browser windows in Protractor. The code snippet being tested is as follows: I create a new browser instance to perform certain tests. When input is entered into the original browser, it should not affect the ne ...

Problems encountered when transferring information from jQuery to PHP through .ajax request

Hey there! I am currently working with Yii and facing an issue while trying to pass some data to a controller method called events. This is how my jQuery ajax call looks like: var objectToSend = { "categories" : [selectedOption],"datefrom" : month + "" + ...

Switching Angular fxLayout from row to column based on a conditional statementHere is an explanation of how to

Visit this link for more information Is there a way to set direction based on a specific value? <div if(value) fxLayout='row' else fxLayout='column'> ...

Ways to minimize the loading time of contents within the Dropdown

I am facing an issue with the loading time of my dropdown list. When trying to load 100,000 items on button click, it takes too long. Is there any way to reduce the loading time? Looping through Products for (int i = 0; i < 100000; i++) { ...

Is it necessary to bump the major version if I make updates to a react module that does not affect existing code functionality, but may cause Jest snapshot tests to break?

Imagine I am developing a module for a react component and currently working on a PR to introduce a new feature. Along with this new feature, I have also made changes to the component by refactoring it to eliminate certain internal parts that were previou ...

Vuetify - Implementing a search feature in a table that automatically navigates to the matching row

Currently, I am working with 2 Vuetify data tables that do not have pagination enabled. Each row in the second table corresponds to exactly one parent in the first table. My goal is to be able to click on an entry in the second table and have it automati ...

What is the best way to track all method calls in a node.js application without cluttering the code with debug statements

How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...

Can a webpage be redirected to another page after an animation using only HTML and CSS?

My goal is to design a landing page that has a button allowing users to trigger an animation before being redirected to another page. This concept involves adding a captivating element before transitioning between pages, similar to a link with a dynamic ...

Using the onClick event to dynamically alter the class name within a mapped array by leveraging Hooks

I'm currently working on developing an answer sheet, commonly known as a "Bubble sheet", where the user has the ability to select either "A,B,C, or D" and see the bubble transition from light mode to dark mode just like when marking with a physical pe ...

Is Vue's method of global component communication accurate?

Creating modal popup components like myPopup.vue for global use. Importing it in both App.vue and main.js to use globally by defining objects within Vue.prototype. Implementing methods in Vue.prototype for handling popups, such as "show" or "hide". Howe ...

Set a div to have both absolute positioning and sticky behavior

Looking to create a div ("profilemenu") that pops out on the right side of the page triggered by a button (I'll handle this part). I want it to have a sticky attribute, but positioning has been tricky. Using position: absolute works for proper placeme ...

What is the best way to display only a specific container from a page within an IFRAME?

Taking the example into consideration: Imagine a scenario where you have a webpage containing numerous DIVs. Now, the goal is to render a single DIV and its child DIVs within an IFrame. Upon rendering the following code, you'll notice a black box ag ...

iOS does not support Css3 Transition

My Transition Code works on PC and android devices, but it does not work on iOS devices. I am only using HTML and CSS. /***** BOX 3 *****/ #box3 { height:240px; width:198px; border:1px solid #dedede; background-color:#fcfcfc; position:relative; overflow:h ...

Is it possible to utilize curly brackets in JavaScript for dividing code segments?

Check out this code snippet. I'm curious if there are any potential drawbacks to using it. //some example code var x = "hello"; { var y = "nice"; function myfunction() { //perform tasks... } } One advantage I see in utilizing t ...

Create a function in JavaScript that generates all possible unique permutations of a given string, with a special consideration

When given a string such as "this is a search with spaces", the goal is to generate all permutations of that string where the spaces are substituted with dashes. The desired output would look like: ["this-is-a-search-with-spaces"] ["this ...

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...