What is the best approach for loading locally stored images conditionally in Vue.js?

<template>
  <div>
    <div v-if="item">
      <h1>Price: {{ item.email }}</h1>
      <v-if item.email=="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670d080f0927000a060e0b4904080a">[email protected]</a>">
        <img :src="../"/>
      </v-if>
    </div>
  </div>
</template>

<script>
import { routerid } from "./routerid";
export default {
  name: "User",
  components: {},
  data() {
    return {
      item: [],
    };
  },
  mounted() {
    this.loadData();
  },
  computed: {
    routeId() {
      return this.$route.params.id;
    },
  },

  watch: {
    routeId() {
      console.log("Reload (route change)");
      this.loadData();
    },
  },

  methods: {
    loadData() {
      console.log("Reloading, ID", this.routeId);
      if (!this.routeId) return;
      routerid(this.$route.params.id).then((item) => {
        this.item = item.data;
      });
    },
  },
};
</script>

How can I conditionally load locally stored images in Vuejs?

I currently have three images stored in the assets folder: https://i.sstatic.net/8yUYJ.png

On the frontend, I want to call these images conditionally. For example, if the email is [email protected], then display the John image stored in the assets folder. Otherwise, do not display it. The same applies to the other images for Derk and Kate.

Do I need to use if-else conditions to load the images based on the email, or is there another way to achieve this?

Code example: https://codesandbox.io/s/combined-logic-api-forked-nzzzwc?file=/src/components/User.vue

API response:

{"address":{"geolocation":{"lat":"-37.3159","long":"81.1496"},"city":"kilcoole","street":"new road","number":7682,"zipcode":"12926-3874"},"id":1,"email":"[email protected]","username":"johnd","password":"m38rmF$","name":{"firstname":"john","lastname":"doe"},"phone":"1-570-236-7033","__v":0}

Note: The email will vary for each ID.

Answer №1

It is advisable to include an image link in your API response by adding an image link column to your database table. Alternatively, you can use the following approach:

<div v-if="item">
  <h1>Price: {{ item.email }}</h1>
  <img :src="getPic(item.email)"/>
</div>

Implement the following method:

getPic(src) {
  return "@/assets/" + src.substring(0, src.lastIndexOf("@")) + ".png"
}

However, it is strongly recommended to store the image link in your database for better efficiency.

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

My Next.js application does not display an error message when the input field is not valid

I've recently developed a currency converter application. It functions properly when a number is provided as input. However, in cases where the user enters anything other than a number or leaves the input field empty, the app fails to respond. I aim t ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

Implement lazy loading functionality in Django to dynamically load data as the user scrolls

Currently, I am developing a web application using Django to showcase the interface and how content is loaded. In my database, there could potentially be thousands of entries, and I am looking for a way to load only a certain number at a time to minimize ...

Having trouble with moving the svg:svg element?

I'm struggling to move an svg element that is nested within another svg. I am trying to directly manipulate the x and y values, but I keep encountering a "read-only" error. I attempted to use transform instead, but it doesn't seem to have any eff ...

Decoding the values in an input field

Can anyone help me with identifying links, numbers, and text in WhatsApp and other app input boxes? I also want to be able to preview the page attached to a link and style these elements separately from other text. I am currently working on a project whe ...

Modify picture properties when listbox is altered using jQuery

I need to set up a unique album gallery display where different folders are selected based on the item chosen in a selectbox. Below is the HTML code: <select name="album" id="album" onChange="changeimage();"> <option value="0" selected disab ...

Limiting Velocity in a Two-Dimensional Spacecraft

Like many others diving into the world of programming, I decided to challenge myself with a spaceship game project. At this point, I have successfully incorporated parallax stars and other essential features expected in a space-themed game. The spacecraft ...

What is the best way to dynamically add a class to the right navigation element in Vue.js when the :class binding only accepts boolean values?

My issue involves implementing a fixed navigation bar with the following structure: <nav class='navigation'> <div :class="{ active: }" @click='scrollTo(".test1")'></div> <div :class=" ...

Having issues with $emitting not working for parent-child components in Vue. Any ideas on what I might be doing incorrectly?

I have a login component that I need to call in the main vue component of App.vue. Within the login vue, when I click on any button, it should activate another vue component using Vue.js router to replace the login page. I have searched for solutions but h ...

IE/Firefox returning empty value for Ajax requests

After spending two days trying to solve the issue, I still can't figure out why this code is failing in IE (v11) and Firefox while working fine in Chrome. I have read many questions on similar topics involving caching problems with multiple Ajax call ...

Utilize a for loop within a query to showcase a modal popup

I have a specific requirement: I want to display a modal popup window based on a for loop using jQuery. I have attempted the following approach, where I want the modal popup to be displayed based on the value of a flag. For example, if the Flag value is 3, ...

Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html: <h1 id="header1">H1</h1> <p>Lorem ipsum</p> <h2 id="header2">H2</h2> <p>lorem ipsum</p> <h2 id="header3">H2</h2> <p>lorem upsum</p ...

Transfer data as JSON from Flask to JavaScript

Having trouble sending data from Flask to JavaScript. I have the information from the database and added it to a dictionary. Now, I want to convert this data into a JSON object in JavaScript to display it on a map. Despite using JSON.parse in JavaScript, i ...

Obtaining the value of an item in an unordered list

Hi everyone, I have been trying to extract the value of <li> elements that display images horizontally. Below is the HTML code I am working with: <div id="layoutInnerOptions"> <ul id="navigationItemsContainer" class="layouts_list"> <l ...

Instructions for utilizing float:left and list-style-type within HTML are as follows: I am currently experiencing issues with implementing the float:left and list-style-type properties in my code

I'm attempting to align a button list to the left using the float: left property and also remove list styles, but for some reason it's not working as expected. //CSS #tus{margin:5px;padding:0;width:640px;height:auto;} #tus ul{margin:0px;padding: ...

No departure animation employed - Polymer

I am working on a project that involves animating a paper-icon-button with spin and opacity effects when hovering over an image using the on-mouseenter and on-mouseleave events. Everything works smoothly when hovering over the image, but I am facing an is ...

Unable to assign a value to a constant within the class constructor

I'm aware that in TypeScript, readonly properties can only be assigned a value within a class constructor. However, I encountered an error while trying to do so inside the constructor of my class, specifically related to an array method handler. class ...

Difficulty arises when Jest tests struggle to interpret basic HTML tags within a React Component

When running test runs, issues arise when using standard HTML tags with Jest. My setup includes Babel, Webpack, Jest, and React Testing Library. To enable jest, I have installed a number of packages: "@babel/plugin-proposal-class-properties": "7.8.3", "@ ...

Click handler that transmits data to a server using ajax

I have been tasked with creating a website using HTML, CSS, and JavaScript that includes three buttons. When clicked, these buttons will send codes such as "10," "01," and "11" to a C++ program. The C++ program will then respond and perform a function base ...

Can the state be determined by the presence of other objects in the state?

Currently, I'm delving into the world of ReactJS by constructing a personalized launch page. Brace yourself for a somewhat casual explanation. Within my primary app.js file, I've set up the initial state of the application with some data like th ...