一、加载速度优化
精灵图
base64
iconfont替代图片
代码压缩
图片、视频压缩
cdn缓存
路由懒加载
原理:将每个组件都打成一个包,首页的大文件可以进行分批引入 实现:main.js中将所有的同步引入组件的方式改为异步引入组件,即: import Home from "pages/Home"改为const Home=()=>import("pages/Home")
二、运行效率优化
减少http请求----<keep-alive></keep-alive>
使用:
<keep-alive> <router-view></router-view> </keep-alive>
原理:使用keep-alive包裹的组件在创建之后不会经历销毁,给不用频繁请求数据的组件包裹
属性:include:包括,表示需要缓存的组件----include="a,b" include="/a|b/" include="["a","b"]"
exclude:除了,表示不需要缓存的组件,不能和include一起使用
max:最多可以缓存多少个组件
增加两个生命周期:
activated:进入该组件时触发,可以用来做数据的请求
deactivated:离开该组件时触发
数据本地化
cookie、localStorage、sessionStorage
localStorage的二次封装:
1、兼容
2、简化读取与存储:JSON的两个方法
3、设置时间限制
export default{ set(key,data,time){ let obj={ data=data, ctime:(new Date()).getTime(),//时间戳,同Date.now() express:1000*60*60//设置过期时间一个小时 } localStorage.setItem(key,JSON.stringify(obj)); }, get(key){ let obj=JSON.parse(localStorage.getItem(key)); let getItem=(new Date()).getTime(); if(getItem-obj.ctime>=express){ localStorage.removeItem(key); return null; }else{ return obj.data; } } }
图片懒加载----可以使用ui框架,也可以使用vue-lazyload插件
vue-lazyload插件的使用:
1、下载依赖:cnpm i vue-lazyload
2、main.js中:
import VueLazyload from 'vue-lazyload' Vue.use(VueLazyload, { preLoad: 1.3, error: require("./assets/vue_lazyload.jpg"), loading: require("./assets/vue_lazyload.jpg"), attempt: 1 })
3、在需要图片懒加载的页面中,使用v-lazy指令替换:src
三、用户体验优化
加载loading条:
1、新建Loading.vue组件
<template> <div class="loading"> <img src="/loading.gif"><!-- 图片在public目录下 --> </div> </template> <script> export default { } </script> <style lang="less" scoped> @import "~style/index.less"; .loading{ position: fixed; background-color: rgba(0,0,0,0.6); width: 100%; .top(0); .bottom(0); display: flex; align-items: center; justify-content: center; img{ .w(50); .h(50); } } </style>
2、在需要网络请求的组件中引入loading组件,loading组件为一个div,设置v-if="loading",loading在data的初始值为true。其他内容为另一个div包裹,设置v-else。当请求完数据后,设置this.loading=false。