Vue3、Vue2动态绑定图片

急着查询Vue3动态引入图片方式?或者vue2动态绑定图片方式?
===>那就,直接滑到底部~

有如下需求:

有一些icon图片,我们存在assets目录下,图片命名为如water.png,fire.png,list 中的格式也都准备好了,如下

list = [
    icon: 'water.png',
    name: '新装',
    path: '/integrated-services/businessAccept/newWater',
    tmplId: 100,
    active: true,
    icon: 'fire.png',
    name: '销户',
    path: '/integrated-services/businessAccept/accountCancellation',
    tmplId: 55,
    active: false,

有些同学想当然==>

 <div v-for="(item, index) in list" :key="item.name + index">
      <img :src="`/src/assets/images/businessAccept/${item.icon}`" />

开发环境也能过

大意了呀,你可以build看看!

一些同学想到了,这里是解析为一个字符串,所以开发环境确实是可以,但是正式环境就不行了,因此要动态引入,vue2中我们用require

vue2 解法

 <div v-for="(item, index) in list" :key="item.name + index">
      <img :src="require(`/src/assets/images/businessAccept/${item.icon}`)" />

再优雅一点??

 <div v-for="(item, index) in list" :key="item.name + index">
      <img :src="getIconUrl(item)" />
// 在methods中:
 methods: {
    getIconUrl(item) {
      return require(`/src/assets/images/businessAccept/${item.icon}`)

vue3中require 写法会报require undefined,因为有新的方式了

Vue3 解法

 <div v-for="(item, index) in list" :key="item.name + index">
      <img :src="getIconUrl(item)" />
// 在methods中:
 methods: {
    getIconUrl(item) {