一、高效调用本地图片资源
1. 图片资源管理
src/
assets/
images/
home/
banner.jpg
logo.png
about/
team.jpg
history.png
2. 引用本地图片
方法一:使用require
<template>
<div>
<img :src="require('@/assets/images/home/banner.jpg')" alt="Banner">
</div>
</template>
方法二:使用import
<template>
<div>
<img :src="bannerImage" alt="Banner">
</div>
</template>
<script>
import bannerImage from '@/assets/images/home/banner.jpg';
export default {
data() {
return {
bannerImage
};
}
};
</script>
方法三:使用Webpack的url-loader
或file-loader
module.exports = {
chainWebpack: config => {
config.module
.rule('images')
.use('url-loader')
.loader('url-loader')
.options({
limit: 8192, // 小于8KB的图片会被转换为Base
name: 'img/[name].[hash:8].[ext]'
});
}
};
二、优化加载性能
1. 图片懒加载
使用Vue-Lazyload插件
首先,安装Vue-Lazyload插件:
npm install vue-lazyload --save
然后在Vue项目中使用:
import Vue from 'vue';
import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'path/to/error.jpg',
loading: 'path/to/loading.gif',
attempt: 1
});
new Vue({
// ...
}).$mount('#app');
在组件中使用:
<template>
<div>
<img v-lazy="'@/assets/images/home/banner.jpg'" alt="Banner">
</div>
</template>
2. 使用CDN加速
将静态资源上传到CDN服务器,可以显著提升资源加载速度,减少服务器负载。
配置CDN
在vue.config.js
中配置publicPath:
module.exports = {
publicPath: 'https://your-cdn-domain.com/'
};
<template>
<div>
<img src="https://your-cdn-domain.com/images/home/banner.jpg" alt="Banner">
</div>
</template>
3. 图片压缩
使用图像处理工具
module.exports = {
chainWebpack: config => {
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
mozjpeg: { progressive: true, quality: 65 },
optipng: { enabled: true },
pngquant: { quality: [0.65, 0.90], speed: 4 },
gifsicle: { interlaced: false },
webp: { quality: 75 }
});
}
};
4. 使用WebP格式
使用Webpack插件
安装webp-webpack-plugin
:
npm install webp-webpack-plugin --save-dev
在vue.config.js
中配置:
const WebPWebpackPlugin = require('webp-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new WebPWebpackPlugin({
quality: 75,
method: 6
})
]
}
};
5. 缓存策略
合理利用浏览器缓存,可以减少重复加载资源,提升页面加载速度。
设置HTTP缓存头
在服务器配置中设置合理的缓存头,例如:
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
三、总结
希望本文的分享能对你有所帮助,在实际项目中灵活运用这些技巧,不断优化和提升项目的性能表现。