<div style="background-image: url(./assets/bj.jpeg);"></div>
以上的代码,在style属性中使用了相对路径,在页面元素上的内容d也没有问题。
但是,背景图片依旧没有出来,甚至报错。
很明显是路径有问题,当然了编写的路径肯定是没问题,但是编译后的文件可就不一定了。
那我们想在style属性中设置背景图片怎么办?
解决一、 使用绝对路径
<div style="background-image: url(/src/assets/bj.jpeg);"></div>
解决二、使用Import + 动态style
<template>
<div :style="{backgroundImage: 'url('+ bj +')'}"></div>
</template>
<script setup>
import bj from './assets/bj.jpeg';
console.log(bj);
</script>
<style>
div {
width: 100%;
min-height: 500px;
background-color: aqua;
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
</style>
本质上,它使用的依然是绝对路径: