Breaking down the steps to flip between two images when clicked in Vue.js

I'm currently trying to implement a feature in Vue.js where images switch on click. The functionality I'm aiming for is as follows:

Upon initial load, the image displays in black, then upon clicking/selecting it, the image transitions into a blue version.

I want this process to be dynamic, but I've encountered some challenges along the way. The images are named imageOne, and upon selection, I want them to change to imageOneBlue. Similarly, I have imageTwo which should switch to imageTwoBlue.

The issue I'm facing is that the images aren't appearing on localhost. I've confirmed that the file paths are accurate because when I test with

<img src="../../assets/images/imageOne.png" />
, the image shows up on the localhost.

Here's the current state of my code:

The component:

<script setup lang="ts">
import { ref, defineProps, computed } from 'vue';

const props = defineProps<{
  imageName: string
}>()

const isBlue = ref(false)

const imageSource = computed(() => {
  return isBlue.value ? `../../assets/images/${props.imageName}Blue.png` : `../../assets/images/${props.imageName}.png`
})

function toggleImage() {
  isBlue.value = !isBlue.value
  // This code below works in the console but the images still don't show up on the screen.
  console.log('isBlue value:', isBlue.value)
}
</script>

<template>
  <div class="option1" @click="toggleImage">
    <div class="leftbox">
      <img :src="imageSource" class="img" />
    </div>
  </div>
</template>

This is where I call the component:

<script setup lang="ts">
import { ref } from 'vue'
import router from '@/router'
import MakeBlue from '../components/MakeBlue.vue'
</script>

<template>
  <div class="container">
    <div class="content-container">
      <div class="option-container">
        <MakeBlue imageName="imageOne" />
        <MakeBlue imageName="imageTwo" />
      </div>
    </div>
  </div>
</template>

Any assistance would be highly appreciated as I am relatively new to Vue.js. Thank you!

Answer №1

If it helps, consider importing the images without using the path.

<script setup lang="ts">
import { ref, defineProps, computed } from 'vue';

const props = defineProps<{
  imageName: string
}>()

const isBlue = ref(false)
const imageSrc = ref('')

const getImageSrc = computed(() => {
  return imageSrc.value
})

function toggleImage() {
  isBlue.value = !isBlue.value

  if(isBlue.value) import(`../../assets/images/${props.imageName}Blue.png`).then(data => imageSrc.value = data.default)
  else import(`../../assets/images/${props.imageName}.png`).then(data => imageSrc.value = data.default)

}
</script>

<template>
  <div class="option1" @click="toggleImage">
    <div class="leftbox">
      <img :src="getImageSrc" class="img" />
    </div>
  </div>
</template>

Answer №2

Perhaps try updating the image path from

../../assets/images/${props.imageName}Blue.png
to
src/assets/images/${props.imageName}Blue.png
. Make sure to make the necessary changes in other sections as well.

I believe this adjustment may assist you in resolving the issue.

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

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

"Attempt to create angular fork results in an unsuccessful build

I have recently created a fork of angularJs and I am facing an issue when trying to build it. The build process fails when running grunt package npm -v --> 3.5.2 bower --version --> 1.7.2 I followed the steps provided in the official documentation ...

Creating a login page with Titanium Appelerator is a breeze

Looking for guidance on creating a login page using Titanium Appcelerator docs. Struggling to grasp the documentation - any recommendations for tutorials on storing user data in a database, accessing it, and implementing a login system? ...

Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the s ...

Coordinating Multiple Angular $http Requests using $q and Managing Errors with $q.catch

Struggling with understanding the correct utilization of Angular's $q and JavaScript's promise API. As a newcomer to Javascript, it's possible I'm making a syntax error. This question appears similar, but isn't an exact duplicate. ...

Presentation of information with loading and error scenarios

How can we effectively display data in an Angular view, considering loading state and error handling? Imagine we are fetching a set of documents from our backend and need to present them in an Angular view. We want to address three possible scenarios by p ...

Is there a way to begin using the :nth-child() selector from the last element instead of the first?

$('button').click(function(){ $('ul').find('li:nth-child(2)').css('color', '#f00') }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> < ...

JQuery does not operate on content that is fetched through ajax requests

I've been struggling with this issue for quite some time now and I just can't seem to figure out what I'm doing wrong. (I suspect it's related to the ajax response) I attempted to upload an image to the server using the uploadifive plu ...

What is the best way to hide the div when scrolling to the top?

Is there a way to hide the circle once it's scrolled to the top? Currently, I can scroll the circle to the top but it remains visible. Upon further exploration, I found that clicking on the circle scrolls it to the top and then on a second click, it f ...

What is the correct method to include basic authentication headers in a post request for retrieving HTML content?

One of the projects I'm currently working on involves a POST endpoint that is protected by basic auth and returns an HTML form. This particular endpoint is hosted using an express server and secured with passport's basic auth. My goal is to creat ...

Button in Angular gets stuck when a touchscreen is long pressed

In my Angular2 application, I am facing an issue with a button when running on a Windows 10 touchscreen PC in Chrome. Normally, the button works fine and executes the click function. However, if the button is held for 1-2 seconds, it gets stuck and fails t ...

What is the most effective way to organize Vuex modules for optimal separation?

What is the most effective way to separate and structure the Vuex Store into modules from an architectural standpoint? I typically create a module for each major route when using Vue router. With this approach of dividing modules by Views, I often encount ...

Is there a way to dynamically register an external component in Vue3 without altering the main project?

In my current project, known as "ProjectMain," I am also working on another project that will act as an extension to ProjectMain - let's call it "MyComponent." My intention is to create MyComponent as a standalone library. My main question is: can I ...

Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists. When I print it like this: {errors[field.name]}, it works. However, {t(errors[field.name]?.toLocaleString())} does not work. import { FieldProps, FormikErrors } ...

Obtain a 404 rendering using EJS in an ExpressJS application

Utilizing express ejs on both my backend and frontend, I have set up a route to display the dashboard on the admin page. However, when attempting to access my URL http://localhost:3000/admin, I am encountering a 404 error when trying to render the view. He ...

Manipulating strings in Discord.js

if(msg.content.includes("[mid]")) { let str = msg.content let pokeID = str.substring( str.indexOf("[mid]") + 5, str.lastIndexOf("[/mid") //get the unique-code for a pokemon ); msg.channel.send ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Color scheme for navigation bar carousel item background color

I have a navigation bar and carousel within the same section. I want to change the background color of both the navigation bar and carousel item when the carousel indicator becomes active. Any suggestions on how to achieve this using a jQuery function? H ...