vue之src图片路径地址动态拼接的方法。

很常见的需求了。根据后台返回的数据,展示本地对应的图片。这个时候,需要对图片地址的src进行拼接。

由于静态资源路径,方式不对,很容易导致地址有问题。

1、方式一:

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

后台返回的数据譬如

menus: [
{
	"icon": "icon_1.png",
	"name: "首页"
},
{
	"icon": "icon_2.png",
	"name: "副页"
}
]

一句话,在:src中,使用require 和模板字符串,就可以拼接引入正确的路径地址。

2、方式二,

:src 绑定一个函数,然后在methods中定义这个函数,函数内部还是使用require来获取到正确的地址后,返回出去。

<template>
<div v-for="(item,index) in menus :key="index>
<img :src="bindIcon(item.icon)" />
<span>{{item.name}}</span>
</div>
</template>
bindIcon(icon) {
	return require("@/assets/images/"+icon);
}

猜你喜欢

转载自blog.csdn.net/qq_42991509/article/details/106806865