vue数据控制图片路径失效?

294 阅读1分钟

在做毕设的时候遇到这个问题,没有难度,但是可能存在有些刚开始学vue的朋友遇见同样的问题。在这记录一下解决方法。

错误思路

<template>
    <img src="@/assets/images/upImages.png" alt="">
    <!-- 图片url是固定的,无法改变 -->
</template>

这是聪明的你想要通过数据控制显示的图片,于是你想到下面的代码,不出意外的错了。结果是页面连图片都不显示。

<template>
    <img :src="imgUrl" alt="">
</template>

<script>
import { defineComponent, ref } from 'vue';
export default defineComponent({
  setup() {
    let imgUrl = ref('@/assets/images/upImages.png')
    // 想要通过变量imgUrl控制img元素显示哪一张图片
     return{
        imgUrl
     }
  }
})
</script>

具体原因我猜测是因为webpack打包之后,各个文件的关系不会保持现在的路径关系,而变量imgUrl存储的字符串并不会改变,所以根据imgUrl字符串存储的路径就找不到图片文件,因此图片不会正常显示。

VUE数据控制图片的解决办法

解决办法是将图片通过模块化导入,img中的src的值设为该变量的值,图片即可正常显示。

ES6模块化导入

import img from 'url'

CommonJs导入

const img = require('url')

示例

对存储图片的变量进行操作,将需要的图片通过import或require导入,然后对数据操作都会反应到img元素中。

<template>
    <img :src="imgUrl" alt="">
    <el-button @click="switchImg">点击切换图片</el-button>
</template>

<script>
import { defineComponent, ref } from 'vue';
import img from '@/assets/images/upImages.png'
const img2 = require('@/assets/images/view.png')
export default defineComponent({
  setup() {
    let imgUrl = ref(img)
    let img2Url = ref(img2)
    let switchImg = function(){
        imgUrl.value = img2Url.value
    }
     return{
        imgUrl,
        switchImg
     }
  }
})
</script>

结果:点击按钮之后图片发生改变