1. 使用public目录
<!-- 在Vue组件中 -->
<img src="/path/to/image.png" alt="description">
2. 使用assets目录
// 在Vue组件的script部分
import image from '@/assets/path/to/image.png';
export default {
data() {
return {
imageUrl: image
};
}
};
// 在模板中使用
<img :src="imageUrl" alt="description">
3. 动态路径
<!-- 在Vue组件的模板中 -->
<template>
<img :src="getImageUrl()" alt="description">
</template>
<script>
export default {
methods: {
getImageUrl() {
// 根据条件计算图片路径
return `/path/to/image.png`;
}
}
};
</script>
4. 解决打包后图片路径问题
4.1 修改Webpack配置
// 在webpack.prod.conf.js中
const config = {
// ...其他配置
output: {
// ...
publicPath: './' // 确保公共路径正确
},
// ...
};
module.exports = config;
4.2 使用绝对路径
如果你使用的是绝对路径,确保路径正确。例如,在CSS中使用:
background: url('/path/to/image.png') no-repeat center center;
4.3 使用相对路径
使用相对路径时,确保路径相对于当前文件正确。
background: url('../path/to/image.png') no-repeat center center;