Vue.js动态图片在使用webpack时无法正常工作。

173
我有一个案例,在我的Vue.js和webpack的web应用程序中,我需要显示动态图片。我想要展示img标签,其中图片的文件名存储在一个变量中。这个变量是一个computed属性,它返回一个Vuex存储变量,该变量在beforeMount生命周期钩子函数中异步地被填充。
<div class="col-lg-2" v-for="pic in pics">
   <img v-bind:src="'../assets/' + pic + '.png'" v-bind:alt="pic">
</div>

然而,当我只是这样做时,它完美地运行。
<img src="../assets/dog.png" alt="dog">

我的情况与这个fiddle类似,但是这里使用的是图片URL,而我用实际文件路径时无法工作。

正确的方法应该是什么?


6
已解决。这个也解决了问题: <v-img :src="require(@/assets/ + items.image)" height="200px"></v-img> - Mohamed Raza
23个回答

5

5
你可以使用try catch块来帮助处理未找到的图片。
getProductImage(id) {
          var images = require.context('@/assets/', false, /\.jpg$/)
          let productImage = ''
          try {
            productImage = images(`./product${id}.jpg`)
          } catch (error) {
            productImage = images(`./no_image.jpg`)
          }
          return productImage
},

4

我在Vue2上尝试了所有的答案,但对我有效的是这样的。

<div class="col-lg-2" v-for="pic in pics">
   <img :src="require(`../assets/${pic.imagePath}.png`)" :alt="pic.picName">
</div>

3

我在使用Gridsome时,这种方法适用于我。

我还使用了 toLowerCase() 方法。

      <img
        :src="
          require(`@/assets/images/flags/${tournamentData.address.country_name.toLowerCase()}.svg`)
        "
      />

1

我遇到了同样的问题。 将 '../assets/' 改为 './assets/' 后,问题得以解决。

 <img v-bind:src="'./assets/' + pic + '.png'" v-bind:alt="pic">

1

我个人使用的最好、最简单的方法是从API中获取数据。

methods: {
       getPic(index) {
    return this.data_response.user_Image_path + index;
  }
 }

getPic方法接受一个参数,即文件名,并返回该文件的绝对路径,可能包括服务器和文件名。

以下是我使用此方法的组件示例:

<template>
    <div class="view-post">
        <div class="container">
     <div class="form-group">
             <label for=""></label>
             <input type="text" class="form-control" name="" id="" aria-describedby="helpId" placeholder="search here">
             <small id="helpId" class="form-text user-search text-muted">search for a user here</small>
           </div>
           <table class="table table-striped ">
               <thead>
                   <tr>
                       <th>name</th>
                       <th>email</th>
                       <th>age</th>
                       <th>photo</th>
                   </tr>
                   </thead>
                   <tbody>
                       <tr v-bind:key="user_data_get.id"  v-for="user_data_get in data_response.data">
                           <td scope="row">{{ user_data_get.username }}</td>
                           <td>{{ user_data_get.email }}</td>
                           <td>{{ user_data_get.userage }}</td>
                           <td><img :src="getPic(user_data_get.image)"  clas="img_resize" style="height:50px;width:50px;"/></td>
                       </tr>

                   </tbody>
           </table>
        </div>

    </div>
</template>

<script>
import axios from 'axios';
export default {
     name: 'view',
  components: {

  },
  props:["url"],
 data() {
     return {
         data_response:"",
         image_path:"",
     }
 },
 methods: {
       getPic(index) {
    return this.data_response.user_Image_path + index;
  }
 },
 created() {
     const res_data = axios({
    method: 'post',
    url: this.url.link+"/view",
   headers:{
     'Authorization': this.url.headers.Authorization,
     'content-type':this.url.headers.type,
   }
    })
    .then((response)=> {
        //handle success
      this.data_response = response.data;
      this.image_path = this.data_response.user_Image_path;
       console.log(this.data_response.data)
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });
 },
}
</script>


<style scoped>

</style>

0

我觉得我无意中找到了这个问题的最佳解决方案! 你需要做的唯一一件事就是从根目录开始寻址。

不起作用

<img :src="'../assets/' + pic + '.png">

工作:

<img :src="'src/assets/' + pic + '.png">

0

我有一个解决方案,你可能想要尝试一下。

定义一个如下的方法

    methods: {
     getFlagImage(flag){
    return new URL('/resources/img/flags/'+flag+'.png', import.meta.url);
    },

    }

然后可以使用已建立的循环调用图像

   <li :class=" 'nav-item', {'active': language === key} " v-for="(value, 
       key)  in locals" :key="value ">
      <a class="dropdown-item"  @click="switchLanguageTo(key)">
        <img :src="getFlagImage(key)"  /> {{value}}
      </a>
  </li>

0

需要转录图像。 对我有效的方法是将图像放在公共文件夹中。即public/assets/img

Dynamic Image Tag:
<div v-for="datum in data">
 <img
     class="package_image"
     style="max-width:200px;"
     alt="Vue logo"
     :src="`./assets/img/${datum.image}`"
 >
<div>

0

截至今天,使用VUE 3 + Typescript & composition AP进行开发,我所做的是将require函数包裹在try catch中以处理崩溃。

computed: {
    getImage() {
        let imgSrc = "";
        try {
            imgSrc = require(`../assets/weather-widget-icons/ww-icon-${this.weatherForecast.main.toLowerCase()}.svg`);
        } catch (error) {
            console.error(`Image '../assets/weather-widget-icons/ww-icon-${this.weatherForecast.main.toLowerCase()}.svg' not found!`);
        }
        return imgSrc;
    }
}

并在图像标签中调用此函数:

<div class="weather-icon">
    <img :src="getImage" :alt="weatherForecast.main" />
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接