当成笔记吧
项目根文件 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>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。