利用Vue中keep-alive,快速实现页面缓存。vue
keep-alive是一个抽象组件:它自身不会渲染一个DOM元素,也不会出如今父组件链中;使用keep-alive包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。git
例如:github
<template> <div id="app"> <!-- 除了Detail页面外其余页面作缓存 --> <keep-alive exclude="Detail"> <router-view/> </keep-alive> </div> </template>keep-alive会缓存命中的组件;exclude定义缓存黑名单,被命中的组件将不会被缓存。vue-router
在App.vue文件中使用了<keep-alive>标签,而后再利用每一个页面的生命周期判断是否再次发起http请求实现页面缓存。缓存
当组件被keep-alive缓存的时候,会出现2个生命周期钩子函数:app
activated:只要页面一被展现,就会执行
deactivated:只要页面即将被隐藏或替换成新页面,就会执行
router-link默认渲染成带有正确连接的
<a>
标签,能够经过配置tag
属性生成别的标签。异步
当事件是绑定在全局window对象上的时候,其余组件也会受到影响。为了不这种影响,须要对全局事件解绑。函数
因为在项目的App.vue使用了keep-alive,因此能够在activated和deactivated这两个钩子函数中分别完成对全局事件的绑定和解绑。工具
activated() { window.addEventListener('scroll', this.handleScroll); }, deactivated() { window.removeEventListener('scroll', this.handleScroll); },
<script> export default { name: 'Home', } </script>
<template> <div> <div class="item" v-for="(item, index) of list" :key="index" > <div class="item-title border-bottom"> <span class="item-title-icon"></span> {{item.title}} </div> <div v-if="item.children" class="item-children"> <detail-list :list="item.children"></detail-list> </div> </div> </div> </template> <script> export default { name: 'DetailList', props: { list: Array } } </script>
var timer = null;
handleTouchMove () {
if (timer) {
clearTimeout(timer)
}
this.timer = setTimeout(() => {
// 执行的操做
}, 16)
}
函数节流的要点:声明一个变量(timer)当标志位,记录当前代码是否在执行。若是空闲(即timer为true),则能够正常触发方法执行。若是代码正在执行,则取消此次方法执行,直接return,这样就能够作到函数减小执行频率。学习
使用异步组件会将js拆分,当使用到当前组件时才加载当前组件的js,而不是首屏加载全部的整合了全部js逻辑的js文件。这在js比较大(至少超多1MB)时使用比较合适,不然增长了http请求。
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Home', // 异步加载 component: () => import('@/pages/home/Home') }, { path: '/city', name: 'City', component: () => import('@/pages/city/City') }, { path: '/detail/:id', name: 'Detail', component: () => import('@/pages/detail/Detail') } ], // 每次切换到新路由时,页面滚到顶部 scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } })
除了在router.js中配置异步组件外,也能在相应页面的components中设置异步组件
// import HomeHeader from './components/Header' export default { name: 'Home', components: { // HomeHeader, HomeHeader: () => import('./components/Header'), }, }