方法1:使用import导入图片
<template>
<div :style="{ backgroundImage: `url(${bgImage})` }"></div>
</template>
<script setup>
// 直接导入图片资源(会解析为最终路径)
import bgImage from '@/assets/background.jpg'
</script>
方法 2:动态路径(使用 new URL)
const imageName = ref('background.jpg') // 可动态修改
const getImageUrl = (name) => {
// 路径相对于当前文件位置(重要!)
return new URL(`../assets/${name}`, import.meta.url).href
}
</script>
这里的url一定是相对位置,使用@/assets 不起作用
简单的静态路径
// 正确路径
const bgImage1 = new URL(`@/assets/img/screen/menu-active.png`, import.meta.url).href;
// 错误路径 (路径中不能有中文)
const bgImage2 = new URL('@/assets/img/screen/menus/曹娥江.png', import.meta.url).href;
方法 3:使用公共目录(public)
<template>
<!-- 直接使用绝对路径(文件放在 public 目录) -->
<div :style="{ backgroundImage: 'url(/images/background.jpg)' }"></div>
</template>
关于以上三种方法适应的注意事项
1、backgroundImage 路径写法
// 正确(使用模板字符串)
backgroundImage: `url(${imageUrl})`
// 错误(缺少 url() 包裹)
`backgroundImage: ${imageUrl}`
2、文件位置
- 静态资源通常放在:
/src/assets - 需要导入
/public - 直接引用
示例目录结构
project-root/
├── public/
│ └── images/ # 直接通过 /images/xxx 访问
│ └── bg.jpg
├── src/
│ ├── assets/ # 需要 import 或 new URL
│ │ └── header.jpg
│ ├── components/
│ │ └── MyComponent.vue
│ └── App.vue
进阶 import.meta.glob 动态引入多个背景图片
<template>
<ul class="navigation">
<li
v-for="item in menus"
:key="item.label"
:style="getItemStyle(item)" >
{{ item.label }}
</li>
</ul>
</template>
<script setup lang="ts">
const props = defineProps<{
pagename?: string;
}>();
// 1. 使用 glob 批量导入图片
const bgModules = import.meta.glob('@/assets/img/screen/menus/*.{jpg,png,webp}', {
eager: true, // 立即加载
import: 'default', // 直接获取默认导出
});
// 2. 转换导入结果为 { 文件名: URL } 的映射表
const bgImageMap = Object.entries(bgModules).reduce((acc, [path, module]) => {
const fileName = path
.split('/')
.pop()
.replace(/\.[^/.]+$/, ''); // 提取不带扩展名的文件名
acc[fileName] = module;
return acc;
}, {});
const menus = ref([
{
label: '第三方监管',
router: 'thirdPartySupervision',
},
{
label: '饮用水源地',
router: 'drinkingWaterSource',
},
{
label: '曹娥江',
router: 'caoeRiver',
},
]);
// 动态获取样式
const getItemStyle = (item) => {
const imageUrl = item.label == props.pagename ? bgImageMap[item.label + '_active'] : bgImageMap[item.label];
return {
backgroundImage: `url(${imageUrl})`,
};
};
</script>
性能优化:
图片较多时使用 eager: false + 按需加载
const bgImages = import.meta.glob('@/assets/bg-images/*.webp');
// 动态加载单张图片
const loadImage = async (name) => {
const module = await bgImages[`/src/assets/bg-images/${name}.webp`]();
return module.default;
};