Here we first assume:
static file directory:src/assets/images/
our target static file is in:src/assets/images/home/home_bg.png
<img :src="require('@/assets/images/home/home_bg.png')" />
Dynamically introduced through require, found an error:
require is not defind
, this is because require is a method belonging to Webpack
The first way (for a single resource file)
import homeBg from 'src/assets/images/home/home_bg.png'
<img :src="homeBg" />
The second method (applicable to multiple resource files, dynamically passing in the file path)
new URL() + import.meta.url
Create a util folder in the src directory, and create a utils.ts file in the folder
// 获取assets静态资源
const getAssetsFile = (url: string) => {
return new URL(`../assets/images/${url}`, import.meta.url).href;
};
export default {
getAssetsFile,
};
import in vue file
<script setup lang="ts">
import util from 'src/util/utils'
</script>
How to use
<template>
<img class="bg-img" :src="util.getAssetsFile('bg.png')" alt="">
</template>
The third way (applicable to multiple resource files, the files imported in this way must be specified to a specific folder path, and the variable passed in can only be the file name, and cannot contain the file path)
For example, there is a home folder under the assets/images file
// 获取assets静态资源
const getAssetsFile = (url: string) => {
const path = `../assets/images/home/${url}`;
const modules = import.meta.glob("../assets/images/home/*");
return modules[path].default;
};
export default {
getAssetsFile,
};
<script setup lang="ts">
import util from 'src/util/utils'
</script>
<template>
<img class="bg-img" :src="util.getAssetsFile('bg.png')" alt="">
</template>
If the background image is imported (be sure to use a relative path)
.bg-box{
background-image: url('../../assets/images/bg.png');
}