使用vue+Element Plus
后台传来的图片地址如果是完整的没问题!
但是如果仅传路径过来为什么会自动补http://localhost:5173
<el-table-column prop="image" label="礼物图标">
<template v-slot="scope">
<div>{{ scope.row.image }}</div>
<img :src="scope.row.image" style="width: 40px; height: 40px"/>
</template>
</el-table-column>
问题描述及分析: 1. 问题背景:使用vue和Element Plus时,后台传来的图片地址在显示的时候会自动补充"http://localhost:5173",导致图片无法正常显示。 2. 问题原因:在Vue中,图片地址如果是以 "/" 或者 "http://" 开头,则会以绝对路径的方式加载;如果是其他非 "/" 或者 "http://" 开头的路径,则会以相对路径的方式加载,并在路径前面加上当前页面的BaseUrl。 3. 解决方案:需要根据传来的图片地址判断其是否为绝对路径,如果不是绝对路径,则手动添加BaseUrl。
解决方案如下:
```html
<el-table-column prop="image" label="礼物图标">
<template v-slot:scope>
<div>{{ scope.row.image }}</div>
<img :src="formatImageUrl(scope.row.image)" style="width: 40px; height: 40px"/>
</template>
</el-table-column>
methods: {
formatImageUrl(imageUrl) {
if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
return imageUrl;
} else {
return 'http://localhost:5173' + imageUrl;
}
}
}
这里通过添加一个formatImageUrl
方法,在模板中调用该方法来处理图片地址。在formatImageUrl
方法中判断传入的图片地址是否以"http://"或"https://"开头,如果是则直接返回该地址,否则在地址前添加"http://localhost:5173"后返回。
这样就可以解决后台传来的图片路径问题,无论是绝对路径还是相对路径都能正常显示了。 ```
被视为本地绝对路径,会自动拼接当前ip
这个自动补全是因为浏览器默认就会这样,拼接一个 你运行的localhost:端口。
如果想不自动补全,你拼接的时候就 做个处理
比如:src= xxx + 后台传过来的路径 总之就是拼接一个完整的路径
或者干脆后台返回完整的路径。