如何在Vue.js中onclick动态切换两个图片

问题描述 投票:0回答:1

我正在尝试在 Vue.js 中单击时切换图像。我的代码无法正常工作,但这就是我想要实现的目标:

加载时图像为黑色,单击/选择后图像切换并变成照片的蓝色版本。

我想让这个充满活力,但遇到了一些问题。这些图像称为

imageOne
,一旦单击,我希望它更改为
imageOneBlue
。我也有
imageTwo
并且希望它切换到
imageTwoBlue

我不确定为什么图像没有显示在本地主机上。我知道文件路径是正确的,因为我进行了类似

<img src="../../assets/images/imageOne.png" />
的测试,它显示在本地主机上。

这是迄今为止我的代码。

组件:

<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>

这是我调用组件的代码:

<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>

非常感谢任何帮助。我是 Vue.js 新手。谢谢你。

javascript typescript vue.js vue-component dynamic-programming
1个回答
0
投票

也许导入图像而不使用路径对您有用。

<script setup>
import image1 from '../../assets/images/image1.png'
import image2 from '../../assets/images/image2.png'

const imageSource = computed(() => {
  return isBlue.value ?  image1 : image2
})
</script>
© www.soinside.com 2019 - 2024. All rights reserved.