当成笔记吧
我的项目根文件 App.vue
<template> <div class="wrap"> <keep-alive :include="cacheArr" :exclude="exclude"> <router-view class="fadeIn"></router-view> </keep-alive> </div></template><script>import { mapGetters, mapMutations} from 'vuex';import { cacheArr, dropConfig } from '@/commponent/KeepAlive'export default { data(){ return{ cacheArr: cacheArr } }, computed:{ ...mapGetters('KeepAlive',[ 'exclude' ]) }, watch:{ '$route':function (to,from) { const dropArr = dropConfig[to.name]; if (dropArr) { dropArr.forEach( name => { this.drop(name); }); } } }, created(){ //控制台测试 是否真的登记 // window.drop = this.drop; }, methods:{ ...mapMutations('KeepAlive',[ 'drop' ]) }}</script>
KeepAlive(全js)
目录KeepAlive --cacheArr.js -dropConfig.js -index.js -store.js
vuex模块-store.js
const KeepAlive = { namespaced: true, strict: process.env.NODE_ENV !== 'production', state: { exclude: '', }, mutations: { drop(state,name){ name = `${name},`; const reg = new RegExp(name,'g'); //外面不存在时再增加 if(!reg.test(state.exclude)){ state.exclude += name; //利用宏工作初始化exclude setTimeout(() => { state.exclude = state.exclude.replace(new RegExp(name,'g'),''); },0); } } }, getters: { exclude(state){ return state.exclude } }}export default KeepAlive ;
dropConfig.js 登记缓存路由配置文件
export default { //路由name-到这个路由要登记的路由 //key 是以后路由 //value 是要登记的路由 "groupHome":[ //缓存的页面路由name 'expertHome', 'bonusRank' ],}
cacheArr.js 须要进行缓存路由配置文件
export default [ //哪个路由须要缓存 间接写路由name 'groupHome',]
index.js 给须要缓存的组件混合一些办法
自身就是一个函数 传入以后组件,会给组件增加mixins来进行混合一些办法
tips: this.unbind();//忽视就好 与主题无关 this.scrollBind(this);//忽视就好 与主题无关 window.scrollTop();//获取滚动条Y地位 window.scrollTotop(***);//设置滚动条 是我的一些外部办法/** * * @param {object} component 组件对象 */function keepAlive(component) { const scrollTop = Symbol('scrollTop'); component.mixins = [{ activated() { if(typeof this.unbind === 'function'){ this.unbind(); this.scrollBind(this); } if (typeof this[scrollTop] != "undefined") { this.$nextTick(() => { window.scrollTotop(this[scrollTop]); }) } }, deactivated(){ if(typeof this.unbind === 'function'){ this.unbind(); } }, beforeRouteLeave(to, from, next) { this[scrollTop] = window.scrollTop(); if(typeof this.unbind === 'function'){ this.unbind(); } next() } }] return component;}export default keepAlive;export { default as cacheArr} from './cacheArr';export { default as dropConfig} from './dropConfig';
应用形式
<template> <div class="home"> </div></template><script>export default KeepAlive({ name: "****",});<script><style scoped>.home{}</style>