How to dynamically switch between two images onclick in Vue.js

41 views Asked by At

I am trying to switch images on click in Vue.js. My code isn't working but this is what I am trying to make happen:

On load the image is black, after clicked/selected the image switches and turns into a blue version of the photo.

I want to make this dynamic but am running into some issues. The images are called imageOne and once clicked, I want it to change to imageOneBlue. I also have imageTwo and want it to switch to imageTwoBlue.

I am not sure why the images aren't showing on the localhost. I know the file paths are correct because I put a test like <img src="../../assets/images/imageOne.png" /> it shows up on the localhost.

Here is my code so far.

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 the code 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 help is greatly appreciated. I am new to Vue.js. Thank you.

1

There are 1 answers

1
Juan Pablo Spiatta On

Maybe it would be useful for you to import the images and not use 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>