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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章