vue keep-alive 使用思路
Posted 咕咕gu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue keep-alive 使用思路相关的知识,希望对你有一定的参考价值。
当成笔记吧
项目根文件 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>
以上是关于vue keep-alive 使用思路的主要内容,如果未能解决你的问题,请参考以下文章
vue.js 源代码学习笔记 ----- keep-alives