我封装了一个组件,用于展示背景图,更具图片比例自适应
<template>
<div
class="bg-img"
:style="getBackground(imgSrc)"
/>
</template>
<script setup lang="ts">
defineProps<{ imgSrc: string }>();
const getBackground = (imgSrc: string) => {
// 然后将编码后的URL传递给backgroundImage属性
return {
background: '#eff1f3 no-repeat center center/contain',
backgroundImage: `url(${encodeURI(imgSrc)})`
};
};
</script>
<style lang="scss" scoped>
.bg-img {
width: 64px;
height: 40px;
}
</style>
但是 当图片路径中带有扩展,则图片就不展示;URL中的括号被编码为了%28和%29,而这可能导致浏览器无法正确识别图片的URL。
解决办法就是给路径带上引号!!!
backgroundImage: `url('${encodeURI(imgSrc)}')`